#!/bin/bash

export DEBIAN_FRONTEND=noninteractive

red="\e[0;91m"
blue="\e[0;94m"
expand_bg="\e[K"
blue_bg="\e[0;104m${expand_bg}"
red_bg="\e[0;101m${expand_bg}"
green_bg="\e[0;102m${expand_bg}"
green="\e[0;92m"
white="\e[0;97m"
bold="\e[1m"
uline="\e[4m"
reset="\e[0m"


details=$(cat /etc/os-release)
dist=$(echo "$details" | grep ^ID= | grep -Eo [a-z]+)
version=$(echo "$details" | grep ^VERSION= | grep -Eo [0-9]+ | head -n 1)

if [ "$EUID" -ne 0 ]
  then echo "Bu uygulamayı yalnızca ROOT kullanıcı ise çalistirabilirsiniz."
  exit
fi
if [ "$dist" != ubuntu ];
  then echo "Bu uygulamayı yalnızca Ubuntu 20 işletim sistemlerinde calistirabilirsiniz."
  exit
fi
if [ "$version" != 20 ];
  then echo "Bu uygulamayı yalnızca Ubuntu 20 işletim sistemlerinde calistirabilirsiniz."
  exit
fi


function menu(){
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}-----------   DiyoCP Sihirbazı    ----------${reset}";
    echo -e "${blue}-----------  ${red}v3.2 ${white}- ${green}diyocp.com  ${blue}----------${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${uline}";
    echo -e "${blue}1) ${red}Kurulum Yap${reset}";
    echo -e "${blue}0) ${white}Çıkış Yap${reset}";
    echo "Lütfen Yapmak İstediğiniz İşlemi Seçin: ";
    read option
    case $option in
        1) install;;
        0) echo "Çıkış Yapıldı";;
        *) clear;menu;;
    esac
}
function install(){
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}-------   DiyoCP Kurulum Sihirbazı   -------${reset}";
    echo -e "${blue}-------     ${red}v3.2 ${white}- ${green}diyocp.com     ${blue}--------${reset}";
    echo -e "${blue}--------------------------------------------${reset}";

    userip="$(curl ifconfig.me 2>/dev/null)";
    read -e -p "Lütfen kurmak istediğiniz alan adını giriniz: " -i "firmaismi.com" domain
    read -e -p "Lütfen bu sunucunun ip adresini giriniz: " -i "${userip}" ipaddress
    read -e -p "Lütfen veri tabanı için bir şifre belirleyin: " -i "" dbpassfix
    read -e -p "Lütfen lisans anahtarınızı giriniz: " -i "" lisance

    clear;
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}---------   Sunucu Güncelleniyor   ---------${reset}";
    echo -e "${red}Bu işlem sunucunuzun hızı ve internete göre ${reset}";
    echo -e "${red}5 dakikaya kadar sürebilir(apt-get upgrade) ${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -ne "#                     (5%)\r";
    test="$(apt-get update -y 2>/dev/null)";
    test="$(apt-get upgrade -y 2>/dev/null)";

    clear;
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}---------   Web Server Kuruluyor   ---------${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -ne "#                     (15%)\r";
    test="$(apt -y install software-properties-common 2>/dev/null)";
    echo -ne "#                     (16%)\r";
    test="$(apt install php7.4 php7.4-common php7.4-opcache php7.4-cli php7.4-gd php7.4-soap php7.4-curl php7.4-mysql php7.4-fpm php7.4-zip php7.4-gd php7.4-bcmath php7.4-imagick php7.4-mbstring php7.4-ssh2 php7.4-cli -y 2>/dev/null)";
    echo -ne "#####                 (20%)\r";
    test="$(systemctl enable php7.4-fpm 2>/dev/null)";
    test="$(systemctl start php7.4-fpm 2>/dev/null)";
    test="$(sed -i -E 's/^(upload_max_filesize\s*=\s*).*/\11024M/; s/^(post_max_size\s*=\s*).*/\11024M/' /etc/php/7.4/cli/php.ini; 2>/dev/null)";
    test="$(sed -i -E 's/^(upload_max_filesize\s*=\s*).*/\11024M/; s/^(post_max_size\s*=\s*).*/\11024M/' /etc/php/7.4/fpm/php.ini; 2>/dev/null)";
    dbpass=$(echo ${dbpassfix} | php -r 'echo str_replace(["`","\"","@","^"],"",file_get_contents("php://stdin"));');
    echo -ne "######                (23%)\r";

    clear;
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}--------  DiyoCP Yazilimi Kuruluyor  -------${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -ne "#########             (28%)\r";
    test="$(apt-get install unzip wget -y; 2>/dev/null)";
    echo -ne "##########            (30%)\r";
    test="$(mkdir /var/www 2>/dev/null)";
    test="$(mkdir /var/www/${domain}; 2>/dev/null)";
    echo -ne "##########            (33%)\r";
    test="$(cd /var/www/${domain};wget https://install.diyocp.com/DiyoCP-lastest.zip --no-check-certificate 2>/dev/null)";
    echo -ne "##########            (38%)\r";
    test="$(cd /var/www/${domain};unzip DiyoCP-lastest.zip 2>/dev/null)";
    test="$(cd /var/www/${domain};rm -rfv DiyoCP-lastest.zip 2>/dev/null)";
    test="$(cd /var/www/${domain}/public_html;chmod 777 app/system.php;chmod 777 app/resources/cache/views;chmod 777 app/resources/cache/views/compiled;chmod 777 app/resources/cache/system.json;chmod 777 app/resources/cache/version.json;chmod 777 app/resources/cache/plugins.json;chmod 777 app/resources/upload;chmod 777 app/resources/update;chmod 777 app/system/cache.php;chmod 777 app/system/loader.php;chmod 777 app/system/viewer.php;chmod 777 app/vendor/upload/upload.php;chmod 777 app/vendor/update/update.php; 2>/dev/null)";
    test="$(cd /var/www/${domain};chown -R www-data:www-data public_html/ 2>/dev/null)";
    test="$(rm -rfv /var/www/${domain}/public_html/.htaccess 2>/dev/null)";
    echo -ne "##########            (43%)\r";

    clear;
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}-----------  Nginx Kuruluyor  ------------${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -ne "#############         (57%)\r";
    test="$(apt install nginx -y 2>/dev/null)";
    test="$(ufw allow 'Nginx HTTP' 2>/dev/null)";
    echo -ne "##############        (58%)\r";
    test="$(systemctl enable nginx.service 2>/dev/null)";
    echo -ne "##############        (58%)\r";
    test="$(systemctl start nginx.service 2>/dev/null)";
    echo -ne "###############       (60%)\r";
    test="$(mkdir /etc/nginx/sites-enabled 2>/dev/null)";
    cat > "/etc/nginx/nginx.conf" <<EOF
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
	worker_connections 1024;
}
http {
	sendfile on;
	tcp_nopush on;
	tcp_nodelay on;
	keepalive_timeout 65;
	types_hash_max_size 4096;
	include /etc/nginx/mime.types;
	default_type application/octet-stream;
	ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
	ssl_prefer_server_ciphers on;
	access_log /var/log/nginx/access.log;
	error_log /var/log/nginx/error.log;
	gzip on;
	include /etc/nginx/conf.d/*.conf;
	include /etc/nginx/sites-enabled/*;
}
EOF
    cat > "/etc/nginx/conf.d/default.conf" <<EOF
server {
	listen 80;
	server_name ${userip};
	root /usr/share/nginx/html;
	index index.php index.html index.htm;
    client_max_body_size 1024M;
	location / {
		try_files \$uri \$uri/ =404;
	}
	error_page 404 /404.html;
	location = /50x.html {
		root /usr/share/nginx/html;
	}
	location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
	}
}
EOF
cat > "/etc/nginx/sites-enabled/${domain}.conf" <<EOF
limit_conn_zone \$binary_remote_addr zone=conn_limit_per_ip:5m;
limit_req_zone \$binary_remote_addr zone=req_limit_per_ip:5m rate=5r/s;

server {
	listen 80;
	server_name ${domain};
	access_log /var/log/nginx/access.log;
	root /var/www/${domain}/public_html;
	index index.php index.html index.htm;

	client_max_body_size 1024M;

	limit_conn conn_limit_per_ip 100;
    limit_req zone=req_limit_per_ip burst=100 nodelay;

	open_file_cache max=200000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
	sendfile on;
	tcp_nopush on;
	tcp_nodelay on;
	reset_timedout_connection on;
	keepalive_timeout 45;
	keepalive_requests 100000;

	error_page 404 /404.html;
	error_page 500 502 503 504 /50x.html;
	location = /50x.html {
		root /usr/share/nginx/html;
	}

    gzip on;
    gzip_min_length 10240;
    gzip_comp_level 1;
    gzip_vary on;
    gzip_disable msie6;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types text/css text/javascript text/xml text/plain text/x-component application/javascript application/x-javascript application/json application/xml application/rss+xml application/atom+xml font/truetype font/opentype application/vnd.ms-fontobject image/svg+xml;

    location / { 
        try_files \$uri \$uri/ /index.php?\$query_string;
    } 
	location ~* ^.+.(jpg|jpeg|gif|css|png|webp|js|ico|svg|ttf|woff|woff2|json)$ {
	    expires 30d;
		etag off;
		if_modified_since off;
		add_header Cache-Control "public, no-transform";
		access_log off;
	}   
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }
}
EOF

    clear;
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}-----------  MySQL Kuruluyor  ------------${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -ne "###############       (65%)\r";
    test="$(apt install mysql-server -y 2>/dev/null)";
    cat > "/etc/mysql/mysql.conf.d/mysqld.cnf" <<EOF
[mysqld]
sql_mode=""
user		= mysql
bind-address		= 127.0.0.1
mysqlx-bind-address	= 127.0.0.1
key_buffer_size		= 16M
myisam-recover-options  = BACKUP
max_connections        = 1453
log_error = /var/log/mysql/error.log
max_binlog_size   = 100M
EOF
    echo -ne "###############       (66%)\r";
    test="$(systemctl enable mysqld.service 2>/dev/null)";
    echo -ne "###############       (67%)\r";
    test="$(systemctl start mysqld.service 2>/dev/null)";
    echo -ne "###############       (68%)\r";
    mysql -sfu root <<EOF
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password by '${dbpass}';
DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
CREATE DATABASE diyocp CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
FLUSH PRIVILEGES;
EOF
test="$(mysql -p -u root -p${dbpass} diyocp < /var/www/${domain}/public_html/diyocp.sql)";
test="$(rm -rfv /var/www/${domain}/public_html/diyocp.sql 2>/dev/null)";
    echo -ne "###############       (80%)\r";

    clear;
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}----------  Görevler Ayarlanıyor -----------${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -ne "###############       (86%)\r";
    test="$(crontab -l > mycron 2>/dev/null)";
    echo -ne "##################    (86%)\r";
    echo "* * * * * /usr/bin/php /var/www/${domain}/public_html/app/task.php > /dev/null 2>&1" >> mycron
    echo -ne "##################    (88%)\r";
    test="$(crontab mycron 2>/dev/null;rm mycron 2>/dev/null)";
    echo -ne "####################  (90%)\r";
    test="$(sed -i "s/sunucuadi.com/${domain}/g" /var/www/${domain}/public_html/app/config/config.php 2>/dev/null)";
    test="$(sed -i "s/Sunucuadi/${domain}/g" /var/www/${domain}/public_html/app/config/config.php 2>/dev/null)";
    test="$(sed -i "s/\"password\" => \"\"/\"password\" => \"${dbpass}\"/g" /var/www/${domain}/public_html/app/config/config.php 2>/dev/null)";
    test="$(service mysql restart 2>/dev/null)";
    test="$(service nginx restart 2>/dev/null)";
    test="$(service php7.4-fpm restart 2>/dev/null)";
    echo -ne "####################  (95%)\r";

    clear;
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}----------    SSL Ayarlanıyor    -----------${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -ne "##################### (97%)\r";
    test="$(apt install certbot python3-certbot-nginx -y 2>/dev/null)";
    echo -ne "##################### (98%)\r";
    test="$(yes | certbot --nginx -d ${domain} -m info@${domain} --agree-tos --non-interactive 2>/dev/null)";
    echo -ne "######################(100%)\r";
    sleep 3;

    clear;
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}-------  Kurulum Tamamlanmak Üzere  --------${reset}";
    echo -e "${red}Lisans edinmek için${reset}";
    echo -e "${green}https://mp.diyocp.com${reset}";
    echo -e "${red}Kurulumu tamamlamak için${reset}";
    echo -e "${green}https://${domain}${reset}";
    echo -e "${red}web sitesini kontrol ediniz${reset}";
    echo -e "${red}Mysql Şifresi: ${reset}";
    echo -e "${red}${dbpass}${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${reset}";
    echo -e "${reset}";
    echo -e "${reset}";

    touch /root/diyocp.ini;
    cat > "/root/diyocp.ini" <<EOF
    ${lisance}
    ${domain}
EOF
}
menu