#!/bin/bash
# Usable dnmp.sh on Debian 8-10.
# Version: Stable-20210520

############################################################
# Core Functions Setup
############################################################
function check_sanity {
	# Do some sanity checking.
	if [ $(/usr/bin/id -u) != "0" ]
	then
		die 'Must be run by root user'
	fi

	if [ ! -f /etc/debian_version ]
	then
		die "Distribution is not supported"
	fi
}

function check_install {
	if [ -z "`which "$1" 2>/dev/null`" ]
	then
		executable=$1
		shift
		while [ -n "$1" ]
		do
			DEBIAN_FRONTEND=noninteractive apt-get -q -y install "$1"
			apt-get clean
			echo "#####################################################"
			print_info "	$1 installed for $executable"
			echo "#####################################################"
			shift
		done
	else
		echo "#####################################################"
		print_warn "	$2 already installed"
		echo "#####################################################"
	fi
}

function check_remove {
	if [ -n "`which "$1" 2>/dev/null`" ]
	then
		DEBIAN_FRONTEND=noninteractive apt-get -q -y  -purge remove "$2"
		apt-get clean
		echo "#####################################################"
		print_info "	$2 removed"
		echo "#####################################################"
	else
		echo "#####################################################"
		print_warn "	$2 is not installed"
		echo "#####################################################"
	fi
}

function check_phpversion {
	if grep ^8.    /etc/debian_version > /dev/null
	then	php_path=/var/run/
			php_ver=php5
	elif grep ^9.  /etc/debian_version > /dev/null
	then	php_path=/run/php/
			php_ver=php7.0
	elif grep ^10. /etc/debian_version > /dev/null
	then	php_path=/run/php/
			php_ver=php7.3
	elif grep ^11. /etc/debian_version > /dev/null
	then	php_path=/run/php/
			php_ver=php7.4
	fi
}

function check_mysqlversion {
	if [ $(lsb_release -sc) = "jessie" ]
	then
		check_install mysqlcommon mysql-common
		mv /etc/mysql/my.cnf /etc/mysql/my.cnf.bak
		rm -f /var/lib/mysql/ib*
		cat > /etc/mysql/my.cnf <<END
[mysqld]
[client]
port			= 3306
socket			= /var/run/mysqld/mysqld.sock


[mysqld_safe]
socket			= /var/run/mysqld/mysqld.sock
nice			= 0

[mysqld]
user			= mysql
pid-file		= /var/run/mysqld/mysqld.pid
socket			= /var/run/mysqld/mysqld.sock
port			= 3306
basedir			= /usr
datadir			= /var/lib/mysql
tmpdir			= /tmp
lc-messages-dir	= /usr/share/mysql
skip-external-locking
bind-address			= 127.0.0.1
key_buffer				= 16K
max_allowed_packet		= 1M
thread_stack			= 64K
thread_cache_size		= 8
myisam-recover			= BACKUP
table_cache				= 20
query_cache_limit		= 1M
query_cache_size		= 2M
log_error = /var/log/mysql/error.log
expire_logs_days		= 10
max_binlog_size			= 100M
skip-innodb
default-storage-engine	= MyISAM

[mysqldump]
quick
quote-names
max_allowed_packet		= 16M

[mysql]

[isamchk]
key_buffer				= 16M

!includedir /etc/mysql/conf.d/
END
	else
		cat > /etc/mysql/conf.d/my.cnf <<END
[mysqld]
key_buffer_size = 8M
query_cache_size = 0
END
	fi
}

function check_hostname {
	if [ -z "$siteurl" ]
	then
		die "Usage: `basename $0` $command <hostname>"
	fi
}

function die {
	echo "ERROR: $1" > /dev/null 1>&2
	exit 1
}

function get_domain_name() {
	# Getting rid of the lowest part.
	domain=${1%.*}
	lowest=`expr "$domain" : '.*\.\([a-z][a-z]*\)'`
	case "$lowest" in
	com|net|org|app|ba|best|biz|blog|cloud|club|cn|co|de|dev|fun|globle|inc|info|io|jp|kyoto|la|life|ltd|me|mobi|moe|name|one|online|osaka|pro|shop|site|space|store|tk|today|tokyo|top|tt|vip|web|website|work|world|wtf|xxx|xyz)
		domain=${domain%.*}
		;;
	esac
	lowest=`expr "$domain" : '.*\.\([a-z][a-z]*\)'`
	[ -z "$lowest" ] && echo "$domain" || echo "$lowest"
}

function get_password() {
	# Check whether our local salt is present.
	SALT=/var/lib/radom_salt
	if [ ! -f "$SALT" ]
	then
		head -c 512 /dev/urandom > "$SALT"
		chmod 400 "$SALT"
	fi
	password=`(cat "$SALT"; echo $1) | md5sum | base64`
	echo ${password:0:13}
}

function print_info {
	echo -n -e '\e[1;36m'
	echo -n $1
	echo -e '\e[0m'
}

function print_warn {
	echo -n -e '\e[1;33m'
	echo -n $1
	echo -e '\e[0m'
}

function remove_unneeded {
	# Remove rsyslogd, which allocates ~30MB privvmpages on an OpenVZ system,
	# which might make some low-end VPS inoperatable. We will do this even
	# before running apt-get update.
	check_remove /usr/sbin/rsyslogd rsyslog
	# Some Debian have portmap installed. We don't need that.
	check_remove /sbin/portmap portmap

	# Other packages that seem to be pretty common in standard OpenVZ
	# templates.
	check_remove /usr/sbin/apache2 'apache2*'
	check_remove /usr/sbin/named 'bind9*'
	check_remove /usr/sbin/smbd 'samba*'
	check_remove /usr/sbin/nscd nscd
	check_remove mysql mysql
	check_remove nginx nginx
	check_remove php 'php*'

	apt-get autoremove
	apt-get autoclean

	# Need to stop sendmail as removing the package does not seem to stop it.
	if [ -f /usr/lib/sm.bin/smtpd ]
	then
		invoke-rc.d sendmail stop
		check_remove /usr/lib/sm.bin/smtpd 'sendmail*'
	fi
}

function remove_dnmp {
	apt-get -q -y remove mysql
	apt-get -q -y remove nginx
	apt-get -q -y remove 'php-*'
	apt-get -q -y remove 'mariadb-*'

	apt-get autoremove
	apt-get autoclean

	rm -rf /etc/mysql/ -R
	rm -rf /var/lib/mysql/ -R
	rm -rf /var/www/
	rm -rf /etc/mysql/
	rm -rf /etc/nginx/
	rm -rf /etc/php/

}

function apt_clean {
	apt-get -q -y autoclean
	apt-get -q -y clean
}

function mkdir_write {
	rm -rf /tmp/$command.$$
	chown -R www-data "/var/www/$siteurl"
	chmod -R 755 "/var/www/$siteurl"
}

function print_admininfo {
	ServerAdmin=""
	read -p "Please input Administrator Email Address:" ServerAdmin
	if [ "$ServerAdmin" == "" ]
	then
		ServerAdmin="webmaster@example.com"
	fi
	echo "==========================="
	echo Server Administrator Email="$ServerAdmin"
	echo "==========================="
}

############################################################
# System Optimization
############################################################
function update_bashrc {
	wget -q http://sh.dnmp.sh/Scripts/Debian/.bashrc -O .bashrc
}

function update_upgrade {
	apt-get -q -y update
	apt-get -q -y upgrade
	apt-get -q -y dist-upgrade

	check_install softwares apt-transport-https lsb-release ca-certificates curl openssl gnupg libc6 perl debconf dialog bsdutils dbus apt apt-utils dselect dpkg  unzip zip libarchive-tools

	apt-get -q -y update
	apt-get -q -y upgrade
}

function install_exim4 {
	check_install mail exim4
	if [ -f /etc/exim4/update-exim4.conf.conf ]
	then
		sed -i "s|dc_eximconfig_configtype='local'|dc_eximconfig_configtype='internet'|g"  /etc/exim4/update-exim4.conf.conf
		invoke-rc.d exim4 restart
	fi
}

function install_syslogd {
	# We just need a simple vanilla syslogd. Also there is no need to log to
	# so many files (waste of fd). Just dump them into
	# /var/log/(cron/mail/messages)
	check_install /usr/sbin/syslogd inetutils-syslogd
	invoke-rc.d inetutils-syslogd stop

	for file in /var/log/*.log /var/log/mail.* /var/log/debug /var/log/syslog
	do
		[ -f "$file" ] && rm -f "$file"
	done
	for dir in fsck news
	do
		[ -d "/var/log/$dir" ] && rm -rf "/var/log/$dir"
	done

	cat > /etc/syslog.conf <<END
*.*;mail.none;cron.none -/var/log/messages
cron.*			-/var/log/cron
mail.*			-/var/log/mail
END

	[ -d /etc/logrotate.d ] || mkdir -p /etc/logrotate.d
	cat > /etc/logrotate.d/inetutils-syslogd <<END
/var/log/cron
/var/log/mail
/var/log/messages {
	rotate 4
	weekly
	missingok
	notifempty
	compress
	sharedscripts
	postrotate
		/etc/init.d/inetutils-syslogd reload >/dev/null
	endscript
}
END

	invoke-rc.d inetutils-syslogd start
}

function install_iptables {
	# Create startup rules
	cat > /etc/iptables.up.rules <<END
*filter

# http://articles.slicehost.com/2010/4/30/ubuntu-lucid-setup-part-1

#  Allows all loopback (lo0) traffic and drop all traffic to 127/8 that doesn't use lo0
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -d 127.0.0.0/8 -j REJECT

#  Accepts all established inbound connections
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

#  Allows all outbound traffic
#  You can modify this to only allow certain traffic
-A OUTPUT -j ACCEPT

# Allows HTTP and HTTPS connections from anywhere (the normal ports for websites)
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 443 -j ACCEPT

# UN-COMMENT THESE IF YOU USE INCOMING MAIL!

# Allows POP (and SSL-POP)
#-A INPUT -p tcp --dport 110 -j ACCEPT
#-A INPUT -p tcp --dport 995 -j ACCEPT

# SMTP (and SSMTP)
#-A INPUT -p tcp --dport 25 -j ACCEPT
#-A INPUT -p tcp --dport 465 -j ACCEPT

# IMAP (and IMAPS)
#-A INPUT -p tcp --dport 143 -j ACCEPT
#-A INPUT -p tcp --dport 993 -j ACCEPT

#  Allows SSH connections (only 3 attempts by an IP every minute, drop the rest to prevent SSH attacks)
-A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --set --name DEFAULT --rsource
-A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 3 --name DEFAULT --rsource -j DROP
-A INPUT -p tcp -m state --state NEW --dport 22 -j ACCEPT

# Allow ping
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT

# log iptables denied calls (Can grow log files fast!)
#-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7

# Misc

# Reject all other inbound - default deny unless explicitly allowed policy
#-A INPUT -j REJECT
#-A FORWARD -j REJECT

# It's safer to just DROP the packet
-A INPUT -j DROP
-A FORWARD -j DROP

COMMIT
END

	# Set these rules to load on startup
	cat > /etc/network/if-pre-up.d/iptables <<END
#!/bin/sh
/sbin/iptables-restore < /etc/iptables.up.rules
END

	# Make it executable
	chmod +x /etc/network/if-pre-up.d/iptables

	# Load the rules
	iptables-restore < /etc/iptables.up.rules

	# You can flush the current rules with /sbin/iptables -F
	echo 'Created /etc/iptables.up.rules and startup script /etc/network/if-pre-up.d/iptables'
	echo 'If you make changes you can restore the rules with';
	echo '/sbin/iptables -F'
	echo 'iptables-restore < /etc/iptables.up.rules'
	echo ' '
}

function install_system {
	remove_unneeded
	update_bashrc
	update_upgrade
	install_exim4
	install_syslogd
#	install_iptables
	apt_clean
}

############################################################
# DNMP Environments
############################################################
function input_sitename {
echo
}

function sources_sury {
	wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
	echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list

	wget -O /etc/apt/trusted.gpg.d/nginx-mainline.gpg https://packages.sury.org/nginx-mainline/apt.gpg
	echo "deb https://packages.sury.org/nginx-mainline/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/nginx.list
}

function sources_stable {
	cp /etc/apt/sources.list /etc/apt/sources.list.backup
	echo "deb http://deb.debian.org/debian stable main" > /etc/apt/sources.list
	echo "deb-src http://deb.debian.org/debian stable main" >> /etc/apt/sources.list
	echo "deb http://deb.debian.org/debian-security/ stable/updates main" >> /etc/apt/sources.list
	echo "deb-src http://deb.debian.org/debian-security/ stable/updates main" >> /etc/apt/sources.list
	echo "deb http://deb.debian.org/debian stable-updates main" >> /etc/apt/sources.list
	echo "deb-src http://deb.debian.org/debian stable-updates main" >> /etc/apt/sources.list
	apt-get update
	apt-get dist-upgrade
}

function sources_testing {
	cp /etc/apt/sources.list /etc/apt/sources.list.backup
	echo "deb http://deb.debian.org/debian testing main" > /etc/apt/sources.list
	echo "deb-src http://deb.debian.org/debian testing main" >> /etc/apt/sources.list
	echo "deb http://deb.debian.org/debian-security/ testing/updates main" >> /etc/apt/sources.list
	echo "deb-src http://deb.debian.org/debian-security/ testing/updates main" >> /etc/apt/sources.list
	echo "deb http://deb.debian.org/debian testing-updates main" >> /etc/apt/sources.list
	echo "deb-src http://deb.debian.org/debian testing-updates main" >> /etc/apt/sources.list
	apt-get update
	apt-get dist-upgrade
}

function install_mysql {
	# Install the MariaDB packages
	check_install mysqld mariadb-server
	check_install mysql mariadb-client

	invoke-rc.d mysql stop

	check_mysqlversion

	invoke-rc.d mysql start

	# Generating a new password for the root user.
	passwd=`get_password root@mysql`
	mysqladmin password "$dbpswd"
	cat > ~/.my.cnf <<END
[client]
user = root
password = $dbpswd
END
	chmod 600 ~/.my.cnf
}

function install_nginx {
	# Need to increase the bucket size for Debian 5.
	if [ ! -d /etc/nginx ]
	then
		mkdir /etc/nginx
	fi
	if [ ! -d /etc/nginx/conf.d ]
	then
		mkdir /etc/nginx/conf.d
	fi
	if [ ! -d /var/www ]
	then
		mkdir /var/www
	fi

	check_install nginx nginx
	
	sed -i "s|worker_processes \[0-9\]|worker_processes $(cat /proc/cpuinfo| grep "processor"| wc -l)|g" /etc/nginx/nginx.conf
	sed -i s|'^user  nginx;'|'user  www-data;'|g /etc/nginx/nginx.conf
	sed -i s|'# gzip_'|'gzip_'|g /etc/nginx/nginx.conf
	invoke-rc.d nginx restart

	cat > /etc/nginx/proxy.conf <<END
proxy_connect_timeout 30s;
proxy_send_timeout   90;
proxy_read_timeout   90;
proxy_buffer_size    32k;
proxy_buffers     4 32k;
proxy_busy_buffers_size 64k;
proxy_redirect     off;
proxy_hide_header  Vary;
proxy_set_header   Accept-Encoding '';
proxy_set_header   Host   \$host;
proxy_set_header   Referer \$http_referer;
proxy_set_header   Cookie \$http_cookie;
proxy_set_header   X-Real-IP  \$remote_addr;
proxy_set_header   X-Forwarded-For \$proxy_add_x_forwarded_for;
END
}

function install_php {
	service mysql stop
	service nginx stop

	check_install php  libicu-dev libjpeg* libmcrypt libapache2-mod-$php_ver $php_ver-common $php_ver-fpm $php_ver-cgi $php_ver-curl $php_ver-mysqlnd $php_ver-mysql $php_ver-sqlite3 $php_ver-xml $php_ver-xml-util $php_ver-xmlrpc $php_ver-gd $php_ver-tidy $php_ver-bcmath $php_ver-gettext $php_ver-net-socket $php_ver-mbstring $php_ver-zip $php_ver-Imagick $php_ver-APC $php_ver-Memcache $php_ver-imap $php_ver-ldap $php_ver-odbc $php_ver-pear $php_ver-intl $php_ver-mhash

	service mysql start
	service nginx start
}

function install_dnmp {
	install_mysql
	install_nginx
	install_php
	apt_clean

	echo ""
	hostnamectl
	echo ""
	mysql -V && nginx -v && php -v
	echo ""
}

function install_phpmyadmin {
#Debian 9以上，Mariadb 10.3、10.4不允许root通过终端命令行以外的方式登录。那我们新建立一个用户，给予root权限不就好了么？
#phpMyAdmin HY000/1698错误的正确解决办法
#首先，在ssh上用root登录mariadb:
#mysql -u root -p
#输入密码成功登录后，建立一个新的用户，并给予最大的权限：
#CREATE USER '新用户'@'%' IDENTIFIED BY '新用户的密码';
#GRANT ALL PRIVILEGES ON *.* TO '新用户'@'%' WITH GRANT OPTION;
#好了，用你的新用户名和密码去登录phpmyadmin吧。Farewell, HY000/1698.

#echo "Creating magento2 database"
#mysql -u root -p12345678 -e "CREATE DATABASE magento2;"
#mysql -u root -p12345678 -e "CREATE USER 'magento2user'@'localhost' IDENTIFIED BY 'm2pass';"
#mysql -u root -p12345678 -e "GRANT ALL ON magento2.* TO 'magento2user'@'localhost' IDENTIFIED BY 'm2pass' WITH GRANT OPTION;"
#mysql -u root -p12345678 -e "FLUSH PRIVILEGES;"


	if [ -z "$1" ]
	then
		die "Usage: `basename $0` phpmyadmin <hostname>"
	fi

	# Downloading the phpmyadmin  latest and greatest distribution.
	mkdir /tmp/phpmyadmin.$$ /var/www/$1

#	if [ $(lsb_release -sc) = "buster" ]
#	then
#		wget -O - https://www.phpmyadmin.net/downloads/phpMyAdmin-latest-all-languages.tar.gz | \
#		tar zxf - -C /tmp/phpmyadmin.$$
#	else
		wget -O - https://files.phpmyadmin.net/phpMyAdmin/4.9.7/phpMyAdmin-4.9.7-all-languages.tar.gz | \
		tar zxf - -C /tmp/phpmyadmin.$$
#	fi

	mv /tmp/phpmyadmin.$$/phpMyAdmin* "/var/www/$1/phpMyAdmin"
	rm -rf /tmp/phpmyadmin.$$
	chown -R www-data "/var/www/$1"
	chmod -R 755 "/var/www/$1"

	sed -i "s|cfg\['blowfish_secret'\] = ''|cfg['blowfish_secret'] = '$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 64)'|g" /var/www/$1/phpMyAdmin/libraries/config.default.php
	sed -i "s|cfg\['blowfish_secret'\] = ''|cfg['blowfish_secret'] = '$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 64)'|g" /var/www/$1/phpMyAdmin/config.sample.inc.php
#	sed -e "s|cfg\['blowfish_secret'\] = ''|cfg['blowfish_secret'] = '$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 64)'|" config.sample.inc.php > config.inc.php

	# Setting up Nginx mapping
	cat > "/etc/nginx/sites-available/$1" <<END
server
	{
		listen		80;
		server_name $1;
		index index.html index.htm index.php default.html default.htm default.php;
		root  /var/www/$1;

		location / {
			try_files \$uri \$uri/ /index.php;
		}

		location ~ \.php$ {
			try_files \$uri =404;
			fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
			include fastcgi_params;
			fastcgi_pass unix:$php_path$php_ver-fpm.sock;
		}

		location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ {
			expires		30d;
		}

		location ~ .*\.(js|css)?$ {
			expires		30d;
		}

		$al
	}
END
	ln -s /etc/nginx/sites-available/$1 /etc/nginx/sites-enabled/$1
	
	nginx -t

invoke-rc.d nginx reload
	
	ServerAdmin=""
	read -p "Please input Administrator Email Address:" ServerAdmin

	if [ "$ServerAdmin" == "" ]
	then
		echo "Administrator Email Address will set to webmaster@example.com!"
		ServerAdmin="webmaster@example.com"
	else
		echo "==========================="
		echo phpMyAdmin Server Administrator Email="$ServerAdmin"
		echo "==========================="
	fi

cat ~/.my.cnf
}

function install_letsencrypt {
	if [ -z "$1" ]
	then
		die "Usage: `basename $0` letsencrypt <hostname>"
	fi

	check_install python3 python3-acme python3-certbot python3-mock python3-openssl python3-pkg-resources python3-pyparsing python3-zope.interface python3-certbot-nginx
	certbot --nginx -d $1
}

function install_vhost {
	check_hostname
	mkdir "/var/www/$siteurl"
	chown -R www-data "/var/www/$siteurl"
	chmod -R 755 "/var/www/$siteurl"

	# Setting up Nginx mapping
	cat > "/etc/nginx/sites-available/$siteurl" <<END
server {
	server_name $siteurl;
	root /var/www/$siteurl;

	location / {
		index index.html index.htm;
	}
}
END
	ln -s /etc/nginx/sites-available/$siteurl /etc/nginx/sites-enabled/$siteurl
	nginx -t
	
	cat > "/var/www/$siteurl/index.html" <<END
Big Brother is watching you!
----$siteurl
END
	invoke-rc.d nginx reload
}

function install_dhost {
	check_hostname
	mkdir "/var/www/$siteurl"
	chown -R www-data "/var/www/$siteurl"
	chmod -R 755 "/var/www/$siteurl"

# Setting up Nginx mapping
	cat > "/etc/nginx/sites-available/$siteurl" <<END
server {
	listen		80;
	server_name $1;
	index index.htm index.html index.php default.htm default.html default.php;
	root  /var/www/$siteurl;

	location / {
		try_files \$uri \$uri/ /index.php;
	}

	location ~ \.php$ {
		try_files \$uri =404;
		fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
		include fastcgi_params;
		fastcgi_pass unix:$php_path$php_ver-fpm.sock;
	}

	location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ {
		expires		30d;
	}

	location ~ .*\.(js|css)?$ {
		expires		12h;
		error_log /dev/null;
		access_log off; 
	}
}
END
	ln -s /etc/nginx/sites-available/$siteurl /etc/nginx/sites-enabled/$siteurl
	
	nginx -t

	cat > "/var/www/$siteurl/index.php" <<END
<?php
	phpinfo();
?>
END
	invoke-rc.d nginx reload
	
}

############################################################
# DNMP Configuration
############################################################
function config_nginx {
	invoke-rc.d nginx stop

	apt-get -q -y update

	sed -i s|'^worker_processes.*;'|'worker_processes auto;'|g /etc/nginx/nginx.conf

	cat > /etc/nginx/conf.d/my.conf <<END
client_max_body_size 20m;
server_names_hash_bucket_size 64;
END

	cat > /etc/nginx/proxy.conf <<END
proxy_connect_timeout	30s;
proxy_send_timeout		90;
proxy_read_timeout		90;
proxy_buffer_size		32k;
proxy_buffers			4 32k;
proxy_busy_buffers_size	64k;
proxy_redirect			off;
proxy_hide_header		Vary;
proxy_set_header		Accept-Encoding '';
proxy_set_header		Host   \$host;
proxy_set_header		Referer \$http_referer;
proxy_set_header		Cookie \$http_cookie;
proxy_set_header		X-Real-IP  \$remote_addr;
proxy_set_header		X-Forwarded-For \$proxy_add_x_forwarded_for;
END

	invoke-rc.d nginx restart
}

function config_php {
#	sed -i s|'^; process.max = 128'|'process.max = 1'|g /etc/php5/fpm/php-fpm.conf
#	sed -i "s|memory_limit = 128M|memory_limit = 2048M|" /etc/php/$php_ver/fpm/php.ini 
echo
}

function setup_mysql {
	# Setting up the MySQL database
	dbname=`echo $siteurl | tr . _`
	# MySQL userid cannot be more than 15 characters long
	dbusid="${dbname:0:15}"
	dbpswd=`get_password "$dbusid@mysql"`

	mysqladmin create "$dbname"
	echo "GRANT ALL PRIVILEGES ON \`$dbname\`.* TO \`$dbusid\`@localhost IDENTIFIED BY '$dbpswd';" | mysql

	cat >> "/root/$siteurl.mysql.txt" <<END
[typecho_myqsl]
dbname = $dbname
userid = $dbusid
passwd = $dbpswd
END

	echo "mysql dbname:" $dbname
	echo "mysql userid:" $dbusid
	echo "mysql passwd:" $dbpswd
	echo "==========================="
}

function setup_nginx {
	# Setting up Nginx mapping
	cat > "/etc/nginx/sites-available/$siteurl" <<END
server {
	listen		80;
	server_name $siteurl;
	index index.html index.htm index.php default.html default.htm default.php;
	root  /var/www/$siteurl;

	location / {
		try_files \$uri \$uri/ /index.php;
	}

	location ~ \.php$ {
		try_files \$uri =404;
		fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
		include fastcgi_params;
		fastcgi_pass unix:$php_path$php_ver-fpm.sock;
	}
	
	location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ {
		expires		30d;
	}

	location ~ .*\.(js|css)?$ {
		expires		30d;
	}

	$al
}
END

	ln -s /etc/nginx/sites-available/$siteurl /etc/nginx/sites-enabled/$siteurl
	
	nginx -t
	invoke-rc.d nginx reload
}

############################################################
# Blogging Platform
############################################################
function install_wordpress {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the Wordpress' latest and greatest distribution.
	wget -O - http://wordpress.org/latest.tar.gz | tar zxf - -C /tmp/$command.$$
	mv /tmp/$command.$$/wordpress "/var/www/$siteurl"
#	rm -rf latest.tar.gz
	
	mkdir_write
	setup_nginx
	print_admininfo
	setup_mysql

	cp "/var/www/$siteurl/wp-config-sample.php" "/var/www/$siteurl/wp-config.php"
	sed -i "s|database_name_here|$dbname|; s/username_here/$dbusid/; s/password_here/$dbpswd/" "/var/www/$siteurl/wp-config.php"
	sed -i "31a define(\'WP_CACHE\', true);"  "/var/www/$siteurl/wp-config.php"
}

function install_typecho {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the typecho's latest and greatest distribution.
	wget -O - http://typecho.org/downloads/1.1-17.10.30-release.tar.gz | tar zxf - -C /tmp/$command.$$
	mv /tmp/$command.$$/build "/var/www/$siteurl"
#	rm -rf latest.tar.gz

	mkdir_write
	setup_nginx
	print_admininfo
	setup_mysql

	sed -i "169s|('dbDatabase', 'typecho')|('dbDatabase', '$dbname')|g" /var/www/$siteurl/install/Mysql.php
	sed -i "160s|('dbUser', 'root')|('dbUser', '$dbusid')|g" /var/www/$siteurl/install/Mysql.php
	sed -i "165s|('dbPassword')|('dbPassword', '$dbpswd')|g" /var/www/$siteurl/install/Mysql.php
}

############################################################
# Forum Platform
############################################################
function install_discuzx {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the DiscuzX's latest and greatest distribution.
	wget https://gitee.com/Discuz/DiscuzX/repository/archive/master.zip
	unzip master.zip -d /tmp/$command.$$
	mv /tmp/$command.$$/DiscuzX/upload "/var/www/$siteurl"
	rm -rf master.zip

	mkdir_write
	setup_nginx
	print_admininfo
	setup_mysql

	sed -i "35s|'ultrax'|'$dbname'|g" /var/www/$siteurl/config/config_global_default.php
	sed -i "31s|'root'|'$dbusid'|g" /var/www/$siteurl/config/config_global_default.php
	sed -i "32s|''|'$dbpswd'|g" /var/www/$siteurl/config/config_global_default.php
}

function install_phpbb {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the phpBB's latest and greatest distribution.
	wget https://download.phpbb.com/pub/release/3.3/3.3.4/phpBB-3.3.4.zip
	unzip phpBB-3.3.4.zip -d   /tmp/$command.$$
	mv /tmp/$command.$$/phpBB3 "/var/www/$siteurl"
	rm -rf phpBB-3.3.4.zip

#	chown -R www-data "/var/www/$siteurl"
#	chmod -R 755 "/var/www/$siteurl"
#	chown -R www-data "/var/www/$siteurl/store"
#	chmod -R 755 "/var/www/$siteurl/store"
#	chown -R www-data "/var/www/$siteurl/cache"
#	chmod -R 755 "/var/www/$siteurl/cache"
#	chown -R www-data "/var/www/$siteurl/files"
#	chmod -R 755 "/var/www/$siteurl/files"
#	chown -R www-data "/var/www/$siteurl/images/avatars/upload"
#	chmod -R 755 "/var/www/$siteurl/images/avatars/upload"

	mkdir_write
	setup_nginx
	print_admininfo
	setup_mysql

#	sed -i "231s|value=\"\"|value=\"$dbname\"|g" /var/www/$siteurl/install/index.php
#	sed -i "236s|value=\"root\"|value=\"$dbusid\"|g" /var/www/$siteurl/install/index.php
#	sed -i "241s|value=\"\"|value=\"$dbpswd\"|g" /var/www/$siteurl/install/index.php
}

function install_carbon {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the Carbon-Forum's latest and greatest distribution.
	wget https://github.com/lincanbin/Carbon-Forum/archive/5.9.0.zip
	unzip 5.9.0.zip -d /tmp/$command.$$
	mv /tmp/$command.$$/Carbon-Forum-5.9.0 "/var/www/$siteurl"
	rm -rf 5.9.0.zip

	mkdir_write
	setup_nginx
	print_admininfo
	setup_mysql

	sed -i "231s|value=\"\"|value=\"$dbname\"|g" /var/www/$siteurl/install/index.php
	sed -i "236s|value=\"root\"|value=\"$dbusid\"|g" /var/www/$siteurl/install/index.php
	sed -i "241s|value=\"\"|value=\"$dbpswd\"|g" /var/www/$siteurl/install/index.php
}

function install_simpleforum {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the simpleforum's latest and greatest distribution.
	wget https://github.com/yujiandong/simpleforum/archive/refs/heads/master.zip
	unzip master.zip -d   /tmp/$command.$$
	mv /tmp/$command.$$/simpleforum-master "/var/www/$siteurl"
	rm -rf master.zip

	mkdir_write
	setup_nginx
	print_admininfo
	setup_mysql

	sed -i "s|\$dbname|\$dbname = '$dbname'|g" /var/www/$siteurl/core/install_update/models/DatabaseForm.php
	sed -i "s|root|$dbusid|g" /var/www/$siteurl/core/install_update/models/DatabaseForm.php
	sed -i "s|\$password|\$password = '$dbpswd'|g" /var/www/$siteurl/core/install_update/models/DatabaseForm.php

	print_warn 'SimpleForum Set Up @ http://'$siteurl'/install.php'
}

function install_flarum {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the Flarum's latest and greatest distribution.
	wget https://gitee.com/FlarumChina/flarum/repository/archive/master.zip
	unzip master.zip -d   /tmp/$command.$$
	mv /tmp/$command.$$/flarum "/var/www/$siteurl"
	rm -rf master.zip

	mkdir_write
	setup_nginx
	print_admininfo
	setup_mysql

#	sed -i "s|\$dbname|\$dbname = '$dbname'|g" /var/www/$siteurl/core/install_update/models/DatabaseForm.php
#	sed -i "s|root|$dbusid|g" /var/www/$siteurl/core/install_update/models/DatabaseForm.php
#	sed -i "s|\$password|\$password = '$dbpswd'|g" /var/www/$siteurl/core/install_update/models/DatabaseForm.php

#	print_warn 'SimpleForum Set Up @ http://$siteurl/install.php'
}

############################################################
# Mall Platform
############################################################
function install_shopxo {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the Shopxo's latest and greatest distribution.
	wget https://github.com/gongfuxiang/shopxo/archive/v2.0.2.zip
	unzip v2.0.2.zip -d  /tmp/$command.$$
	mv /tmp/$command.$$/shopxo-2.0.2 "/var/www/$siteurl"
	rm -rf v2.0.2.zip

	mkdir_write
	setup_nginx
	print_admininfo
	setup_mysql


	sed -i "s|placeholder=\"数据库名\" value=\"shopxo\"|placeholder=\"数据库名\" value=\"$dbname\"|g" "/var/www/$siteurl/application/install/view/index/create.html"
	sed -i "s|placeholder=\"数据库用户名\" value=\"\"|placeholder=\"数据库用户名\" value=\"$dbusid\"|g" "/var/www/$siteurl/application/install/view/index/create.html"
	sed -i "s|placeholder=\"数据库密码\" value=\"\"|placeholder=\"数据库密码\" value=\"$dbpswd\"|g" "/var/www/$siteurl/application/install/view/index/create.html"
}

function install_imgurl {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the ImgURL's latest and greatest distribution.
	wget https://github.com/helloxz/imgurl/archive/refs/heads/master.zip
	unzip master.zip -d  /tmp/$command.$$
	mv /tmp/$command.$$/imgurl-master "/var/www/$siteurl"
	rm -rf master.zip

	mkdir_write
	setup_nginx
}

function install_onenav {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the ImgURL's latest and greatest distribution.
	wget https://github.com/helloxz/onenav/archive/refs/heads/main.zip
	unzip main.zip -d  /tmp/$command.$$
	mv /tmp/$command.$$/onenav-main "/var/www/$siteurl"
	rm -rf main.zip

	mkdir_write
	setup_nginx
	print_admininfo
	setup_mysql

	cp "/var/www/$siteurl/config.simple.php" "/var/www/$siteurl/data/config.php"
	sed -i "s|database_name_here|$dbname|; s|username_here|$dbusid|; s|password_here|$dbpswd|" "/var/www/$siteurl/wp-config.php"
}

############################################################
# Mail Platform
############################################################
function install_rainloop {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the Rainloop' latest and greatest distribution.
	wget http://repository.rainloop.net/v2/webmail/rainloop-latest.zip
	unzip master.zip -d  /tmp/$command.$$
	mv /tmp/$command.$$/imgurl-master "/var/www/$siteurl"
	rm -rf master.zip

	mkdir_write
	setup_nginx
	print_admininfo
	setup_mysql

	cat > "/var/www/$siteurl/.htaccess" <<END
	php_value upload_max_filesize 8m
	php_value post_max_size 25m
END
}

############################################################
# Directory List Platform
############################################################
function install_dlister {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the DirectoryLister' latest and greatest distribution.
	wget -O - https://github.com/DirectoryLister/DirectoryLister/releases/download/3.7.9/DirectoryLister-3.7.9.tar.gz | tar zxf - -C /tmp/$command.$$
	mv /tmp/$command.$$ "/var/www/$siteurl"
#	rm -rf DirectoryLister-3.7.9.tar.gz

	mkdir_write
	setup_nginx

	mv "/var/www/$siteurl/.env.example" "/var/www/$siteurl/.env"
}

function install_EDL {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the directorylister' latest and greatest distribution.
	wget https://github.com/XnSger/EvoDire/archive/refs/heads/master.zip
	unzip master.zip -d  /tmp/$command.$$
	mv /tmp/$command.$$/EvoDire-master "/var/www/$siteurl"
	rm -rf master.zip

	mkdir_write
	setup_nginx
}

function install_h5ai {
	check_hostname
	mkdir /tmp/$command.$$

	apt-get update 
	apt-get -q -y install ffmpeg
	apt-get -q -y install imagemagick
	apt-get -q -y install software-properties-common
	add-apt-repository ppa:kirillshkrogalev/ffmpeg-next 

	# Downloading the h5ai's latest and greatest distribution.
	wget  https://release.larsjung.de/h5ai/h5ai-0.30.0.zip
	unzip h5ai-0.30.0.zip -d  /tmp/$command.$$
	mv /tmp/$command.$$ "/var/www/$siteurl"
	rm -rf h5ai-0.30.0.zip

	mkdir_write
	setup_nginx

	sed -i "s|default.php;|default.php \"/_h5ai/public/index.php\";|g" "/etc/nginx/sites-available/$siteurl"
}

function install_TFM {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the TinyFileManager's latest and greatest distribution.
	wget  https://github.com/prasathmani/tinyfilemanager/archive/refs/heads/master.zip
	unzip master.zip -d  /tmp/$command.$$
	mv /tmp/$command.$$/tinyfilemanager-master "/var/www/$siteurl"
	rm -rf master.zip

	mkdir_write
	setup_nginx

	mv "/var/www/$siteurl/config-sample.php" "/var/www/$siteurl/config.php"
	mv "/var/www/$siteurl/tinyfilemanager.php" "/var/www/$siteurl/index.php"

	print_warn 'Login Details : admin:admin@123 for Admin| user:12345 for User'

}

function install_zdir {
	check_hostname
	mkdir /tmp/$command.$$

	# Downloading the zdir's latest and greatest distribution.
	wget  https://github.com/helloxz/zdir/archive/refs/heads/master.zip
	unzip master.zip -d  /tmp/$command.$$
	mv /tmp/$command.$$/zdir-master "/var/www/$siteurl"
	rm -rf master.zip

	mkdir_write
	setup_nginx

	mv "/var/www/$siteurl/config.simple.php" "/var/www/$siteurl/config.php"
}

############################################################
# Start of DNMP Install Script
############################################################
export PATH=/bin:/usr/bin:/sbin:/usr/sbin

function dnmp_install {
check_sanity
check_phpversion
command=$1
siteurl=$2
phpfmppath="$(ls $php_path$php_ver-fpm.sock | head -n 1)"

if ! type wget >/dev/null 2>&1; then
	apt-get -q -y install wget;
fi

case "$1" in

remove)
	remove_unneeded
	;;
undnmp)
	remove_dnmp
	;;
system)
	install_system
	;;
dnmp)
	install_system
	check_phpversion
	install_dnmp
	;;
stable)
	sources_stable
	install_system
	check_phpversion
	install_dnmp
	;;
testing)
	sources_testing
	install_system
	check_phpversion
	install_dnmp
	;;
sury)
	sources_sury
	install_system
	mkdir_www
	install_dnmp
	;;
mysql)
	install_mysql
	;;
nginx)
	install_nginx
	;;
php)
	install_php
	;;
phpmyadmin)
	install_phpmyadmin $2
	;;
letsencrypt)
	install_letsencrypt $2
	;;
filesize)
	install_filesize $2
	;;
vhost)
	install_vhost $2
	;;
dhost)
	install_dhost $2
	;;
website)
	install_website $2
	;;
wordpress)
	install_wordpress $2
	;;
typecho)
	install_typecho $2
	;;
discuzx)
	install_discuzx  $2
	;;
carbon)
	install_carbon  $2
	;;
sf)
	install_simpleforum  $2
	;;
flarum)
	install_flarum  $2
	;;
phpbb)
	install_phpbb  $2
	;;
dlister)
	install_dlister  $2
	;;
edl)
	install_EDL  $2
	;;
h5ai)
	install_h5ai  $2
	;;
tfm)
	install_TFM  $2
	;;
zdir)
	install_zdir  $2
	;;
shopxo)
	install_shopxo  $2
	;;
drupal)
	install_drupal  $2
	;;
joomla)
	install_joomla  $2
	;;
imgurl)
	install_imgurl  $2
	;;
onenav)
	install_onenav  $2
	;;
rainloop)
	install_rainloop  $2
	;;
*)
	echo -n -e '\e[1;31m'
	echo -n 'Usage:' `basename $0` '[option]'
	echo -e '\e[0m'
	echo -n -e '\e[1;31m'
	echo -n 'Available option:'
	echo -e '\e[0m'
	echo	'#######################'
	print_info 'DNMP Environments		:'
	print_warn 'undnmp system mysql nginx php dnmp stable testing sury'
	print_info 'Website Configuration	:'
	print_warn 'phpmyadmin letsencrypt vhost dhost'
	print_info 'Blogging & CMS Platform	:'
	print_warn 'wordpress drupal joomla'
	print_info 'Forum Platform			:'
	print_warn 'discuzx phpbb carbon sf flarum'
	print_info 'Directory List Platform	:'
	print_warn 'dlister edl h5ai tfm zdir'
	print_info 'Mall Client				:'
	print_warn 'shopxo'
	print_info 'Picture Bed				:'
	print_warn 'imgurl onenav rainloop'
esac
}


dnmp_install $1 $2 $3| tee -a /root/install.log