#!/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}-----------   DiyoVM Sihirbazı    ----------${reset}";
    echo -e "${blue}-----------  ${red}v3.2 ${white}- ${green}diyovm.com  ${blue}----------${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${uline}";
    echo -e "${blue}1) ${red}Kurulum Yap${reset}";
    echo -e "${blue}2) ${red}Lisansı Güncelle${reset}";
    echo -e "${blue}3) ${red}Şifre Değiştir${reset}";
    echo -e "${blue}4) ${red}IP Yasaklama Kaldır${reset}";
    echo -e "${blue}5) ${red}Araci Aktiflestir${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;;
        2) newlisance;;
        3) changepassword;;
        4) ipremove;;
        5) activate;;
        0) echo "Çıkış Yapıldı";;
        *) clear;menu;;
    esac
}
function install(){
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}-------   DiyoVM Kurulum Sihirbazı   -------${reset}";
    echo -e "${blue}-------     ${red}v3.2 ${white}- ${green}diyovm.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 "diyovm.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-curl php7.4-mysql php7.4-fpm php7.4-zip php7.4-gd php7.4-bcmath php7.4-imagick 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)";
    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}--------  DiyoVM 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.diyovm.com//DiyoVM-lastest.zip --no-check-certificate 2>/dev/null)";
    echo -ne "##########            (38%)\r";
    test="$(cd /var/www/${domain};unzip DiyoVM-lastest.zip 2>/dev/null)";
    test="$(cd /var/www/${domain};rm -rfv DiyoVM-lastest.zip 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}-----------  IonCube Kuruluyor  ------------${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -ne "###########           (46%)\r";
    test="$(cd /tmp;wget --no-check-certificate https://install.diyovm.com/ioncube/ioncube_loaders_lin_x86-64.tar.gz;tar -zxvf ioncube_loaders_lin_x86*; 2>/dev/null)";
    echo -ne "############          (49%)\r";
    test="$(cp /tmp/ioncube/ioncube_loader_lin_7.4.so /usr/lib/php/20190902 2>/dev/null)";
    echo -ne "#############         (50%)\r";
    test="$(cd /tmp;rm -rfv * 2>/dev/null)";
    test="$(sed -i 's/engine = On/engine = On\nzend_extension = \/usr\/lib\/php\/20190902\/ioncube_loader_lin_7.4.so/g' /etc/php/7.4/cli/php.ini; 2>/dev/null)";
    test="$(sed -i 's/engine = On/engine = On\nzend_extension = \/usr\/lib\/php\/20190902\/ioncube_loader_lin_7.4.so/g' /etc/php/7.4/fpm/php.ini; 2>/dev/null)";
    echo -ne "#############         (55%)\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;
	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
server {
    listen 80;
    server_name ${domain};
    root /var/www/${domain}/public_html;
    index index.php index.html index.htm;
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
    location / { 
        try_files \$uri \$uri/ /index.php?\$query_string;
    } 
    location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|svg|ttf|woff|woff2)$ {
        access_log off;
        expires 30d;
    }   
    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 diyovm CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
FLUSH PRIVILEGES;
EOF
test="$(mysql -p -u root -p${dbpass} diyovm < /var/www/${domain}/public_html/diyovm.sql)";
test="$(rm -rfv /var/www/${domain}/public_html/diyovm.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/tasks/createserver.php > /dev/null 2>&1" >> mycron
    echo "* * * * * /usr/bin/php /var/www/${domain}/public_html/app/tasks/limitserver.php > /dev/null 2>&1" >> mycron
    echo "*/5 * * * * /usr/bin/php /var/www/${domain}/public_html/app/tasks/infomachine.php > /dev/null 2>&1" >> mycron
    echo "* * * * * /usr/bin/php /var/www/${domain}/public_html/app/tasks/statserver.php > /dev/null 2>&1" >> mycron
    echo "* * * * * /usr/bin/php /var/www/${domain}/public_html/app/tasks/checktask.php > /dev/null 2>&1" >> mycron
    echo "0 * * * * /usr/bin/php /var/www/${domain}/public_html/app/tasks/checkproduct.php > /dev/null 2>&1" >> mycron
    echo "*/5 * * * * /usr/bin/php /var/www/${domain}/public_html/app/tasks/checkapi.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://www.diyovm.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/diyovm.ini;
    cat > "/root/diyovm.ini" <<EOF
    ${lisance}
    ${domain}
EOF
}
function newlisance(){
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}----------    Lisans Değişimi    -----------${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${reset}";
    read -e -p "Lütfen yeni lisans anahtarınızı giriniz: " -i "" newlisance
    lisance="$(cat /root/diyovm.ini | head -1 | tail -1)";
    if [ -z "${lisance-unset}" ]; then
        activate;
    fi
    domain="$(cat /root/diyovm.ini | head -2 | tail -1)";
    userip="$(curl ifconfig.me 2>/dev/null)";
    response="$(/usr/bin/php /var/www/${domain}/public_html/app/tasks/managament.php php ${lisance} lisance ${newlisance} ${domain} ${userip})";
    status=$(echo ${response} | php -r 'echo @json_decode(file_get_contents("php://stdin"),true)['status'] == true ? 1:0;');
    message=$(echo ${response} | php -r 'echo @json_decode(file_get_contents("php://stdin"),true)['message'];');
    if [[ "${status}" == 1 ]]; then
        echo -e "${blue}${message}${reset}";
        echo -e "${uline}";
        menu;
    else
        echo -e "${red}${message}${reset}";
        echo -e "${uline}";
        echo -e "${uline}";
        newlisance;
    fi
}
function changepassword(){
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}----------    Şifre Değişimi    -----------${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${reset}";
    read -e -p "Lütfen mail adresinizi giriniz: " -i "" mail
    read -e -p "Lütfen yeni şifrenizi giriniz: " -i "" newpassword
    lisance="$(cat /root/diyovm.ini | head -1 | tail -1 | xargs echo -n)";
    if [ -z "${lisance-unset}" ]; then
        activate;
    fi
    domain="$(cat /root/diyovm.ini | head -2 | tail -1 | xargs echo -n)";
    response="$(/usr/bin/php /var/www/${domain}/public_html/app/tasks/managament.php php ${lisance} resetpassword ${mail} ${newpassword})";
    status=$(echo ${response} | php -r 'echo @json_decode(file_get_contents("php://stdin"),true)['status'] == true ? 1:0;');
    message=$(echo ${response} | php -r 'echo @json_decode(file_get_contents("php://stdin"),true)['message'];');
    if [[ "${status}" == 1 ]]; then
        echo -e "${blue}${message}${reset}";
        echo -e "${uline}";
        menu;
    else
        echo -e "${red}${message}${reset}";
        echo -e "${uline}";
        echo -e "${uline}";
        changepassword;
    fi
}
function ipremove(){
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}----------   IP Yasak Kaldirma   -----------${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${reset}";
    read -e -p "Yasağı kaldırıcağınız ip adresinizi giriniz: " -i "" ipaddress
    lisance="$(cat /root/diyovm.ini | head -1 | tail -1 | xargs echo -n)";
    domain="$(cat /root/diyovm.ini | head -2 | tail -1 | xargs echo -n)";
    if [ -z "${lisance-unset}" ]; then
        activate;
    fi
    response="$(/usr/bin/php /var/www/${domain}/public_html/app/tasks/managament.php php ${lisance} ipban ${ipaddress})";
    status=$(echo ${response} | php -r 'echo @json_decode(file_get_contents("php://stdin"),true)['status'] == true ? 1:0;');
    message=$(echo ${response} | php -r 'echo @json_decode(file_get_contents("php://stdin"),true)['message'];');
    if [[ "${status}" == 1 ]]; then
        echo -e "${blue}${message}${reset}";
        echo -e "${uline}";
        menu;
    else
        echo -e "${red}${message}${reset}";
        echo -e "${uline}";
        echo -e "${uline}";
        ipremove;
    fi
}

function activate(){
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}-------   DiyoVM Sistem Tanımlama   -------${reset}";
    echo -e "${blue}-------     ${red}v3.2 ${white}- ${green}diyovm.com     ${blue}--------${reset}";
    echo -e "${red}Bu sayfayı görme nedeninizin sebebi${reset}";
    echo -e "${red}diyovm'in eskiden kurulmuş olması olabilir${reset}";
    echo -e "${red}lütfen araca diyovm bilgilerinizi giriniz${reset}";
    echo -e "${blue}--------------------------------------------${reset}";

    read -e -p "Lütfen alan adını giriniz: " -i "diyovm.diyovm.com" domain
    read -e -p "Lütfen lisans anahtarınızı giriniz: " -i "" lisance

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

menu