#!/bin/bash

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"

function menu(){
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}-----------   DiyoVM Sihirbazı    ----------${reset}";
    echo -e "${blue}-----------  ${red}v3.2 ${white}- ${green}diyosoftware.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}diyosoftware.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.diyosoftware.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(yum update) ${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    test="$(setenforce 0 2>/dev/null;service firewalld stop 2>/dev/null;systemctl disable firewalld 2>/dev/null;sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config 2>/dev/null)";
    echo -ne "#                     (5%)\r";
    test="$(yum update -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="$(yum install epel-release yum-utils -y 2>/dev/null)";
    echo -ne "#                     (16%)\r";
    test="$(rpm -Uvh https://repo.diyosoftware.com/diyovm/kurulum-dosyalari/remi-release-7.rpm 2>/dev/null)";
    echo -ne "###                   (17%)\r";
    test="$(rpm -Uvh https://repo.diyosoftware.com/diyovm/kurulum-dosyalari/mysql-community-release-el7-5.noarch.rpm 2>/dev/null)";
    echo -ne "#####                 (18%)\r";
    test="$(yum --enablerepo=remi-php74 install php php-common php-opcache php-cli php-curl php-mysqlnd php-ssh2 php-mysql php-xml php-soap php-xmlrpc php-mbstring php-json php-gd php-mcrypt php-zip php-fpm -y 2>/dev/null)";
    echo -ne "#####                 (20%)\r";
    test="$(systemctl enable php-fpm 2>/dev/null)";
    test="$(systemctl start php-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="$(yum install unzip wget -y; 2>/dev/null)";
    echo -ne "##########            (30%)\r";
    test="$(mkdir /var/www/${domain}; 2>/dev/null)";
    echo -ne "##########            (33%)\r";
    test="$(cd /var/www/${domain};wget https://repo.diyosoftware.com/diyovm/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}/public_html;chmod 777 chmod.sh;./chmod.sh 2>/dev/null)";
    test="$(rm -rfv /var/www/${domain}/public_html/chmod.sh 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://repo.diyosoftware.com/diyovm/kurulum-dosyalari/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/lib64/php/modules 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\/lib64\/php\/modules\/ioncube_loader_lin_7.4.so/g' /etc/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="$(yum install nginx -y 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 nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
include /usr/share/nginx/modules/*.conf;
events {
    worker_connections 1024;
}
http {
    log_format  main  '\$remote_addr - \$remote_user [\$time_local] "\$request" '
                      '\$status \$body_bytes_sent "\$http_referer" '
                      '"\$http_user_agent" "\$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;
    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;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;
        include /etc/nginx/default.d/*.conf;
        error_page 404 /404.html;
            location = /404.html {
        }
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}
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$ {
		try_files \$uri =404;
		fastcgi_pass 127.0.0.1:9000;
		fastcgi_index index.php;
		fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
		include fastcgi_params;
	}
}
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$ {
        try_files \$uri =404;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        include fastcgi_params;
    }
}
EOF

    clear;
    echo -e "${blue}--------------------------------------------${reset}";
    echo -e "${blue}-----------  MySQL Kuruluyor  ------------${reset}";
    echo -e "${blue}--------------------------------------------${reset}";
    echo -ne "###############       (65%)\r";
    test="$(yum install mysql-server -y 2>/dev/null)";
    echo -ne "###############       (66%)\r";
    test="$(systemctl enable mysqld.service 2>/dev/null)";
    echo -ne "###############       (67%)\r";
    test="$(systemctl start mysqld.service 2>/dev/null)";
    test="$(sed -i 's/sql_mode/#sql_mode/g' /etc/my.cnf 2>/dev/null)";
    echo -ne "###############       (68%)\r";
    mysql -sfu root <<EOF
UPDATE mysql.user SET Password=PASSWORD('${dbpass}') WHERE User='root';
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 2>/dev/null)";
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 php-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="$(yum install 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.diyosoftware.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}diyosoftware.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.diyosoftware.com" domain
    read -e -p "Lütfen lisans anahtarınızı giriniz: " -i "" lisance

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

menu