#!/bin/bash

#############################################################################
# Copyright(c) 2021 Admin-Ahead Server Technologies. All rights Reserved.   #
# This code is subject to the Admin-Ahead license.                          #
# Unauthorized copying is prohibited.                                       #
# Support: support@admin-ahead.com                                          #
# Web: https://admin-ahead.com                                              #
#############################################################################

trap '' SIGINT SIGQUIT SIGTERM
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
version="v4.1.14"
repo_base="http://rep0.admin-ahead.com/sources/gDNS"
api_docroot=/var/www/html
dev_preview=0
pkg="gdns-edge.tgz"
CP=$(whereis cp 2>/dev/null | awk '{print $2}')
[[ -z $CP ]] && CP="\cp"

#colors
end='\033[0m'
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
blue='\033[0;34m'
bold='\033[1m'

echo -e "${blue}${bold}Checking required cli utilities...${end}"
yum install which -y >/dev/null 2>&1
[[ $? -ne 0 ]] && apt install which -y >/dev/null 2>&1
echo -e "${green}${bold}OK...${end}"

export OS_TYPE=1
export PKG_MGR=$(which dnf 2>/dev/null)
if [[ -z $PKG_MGR ]];then
    PKG_MGR=$(which yum 2>/dev/null)
    if [[ -z $PKG_MGR ]];then
        PKG_MGR=$(which apt 2>/dev/null)
        if [[ -z $PKG_MGR ]];then
            echo 'Package manager is not suitable !'
            exit 254
        fi
        OS_TYPE=3
    else
        OS_TYPE=2
    fi
else
    $PKG_MGR update -y >/dev/null 2>&1
    if [[ $? -gt 0 ]];then
        sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*
        sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*
        $PKG_MGR update -y >/dev/null 2>&1
        sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*
        sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*        
        $PKG_MGR update -y >/dev/null 2>&1
    fi
fi
export PKG_MGR
export OS_TYPE
for pkgs in wget curl net-tools tar;do $PKG_MGR install $pkgs -y >/dev/null 2>&1;done

# main functions

manageFirewall() {
    #Disable SELinux
    setenforce 0 >/dev/null 2>&1
    if [[ -e "/etc/selinux/config" ]];then
        [[ ! -e "/etc/selinux/config.aast" ]] && $CP -fp /etc/selinux/config{,.aast} && sed -i "/^SELINUX=/c\SELINUX=disabled" /etc/selinux/config
        [[ $(grep -ic 'SELINUX=disabled' "/etc/selinux/config") -gt 0 ]] && notify success "SELinux disabled - success" || notify warning "SELinux disabled - failed"
    fi

    if [[ -n $(which firewall-cmd 2>/dev/null) ]];then
        $PKG_MGR remove firewalld -y >/dev/null 2>&1
        [[ $PKG_MGR == apt ]] && $PKG_MGR purge firewalld -y >/dev/null 2>&1
    fi
    if [[ $OS_TYPE -eq 3 ]]; then
		echo iptables-persistent iptables-persistent/autosave_v4 boolean true | debconf-set-selections
		echo iptables-persistent iptables-persistent/autosave_v6 boolean true | debconf-set-selections
		iptin="iptables iptables-persistent"
	else
		iptin="iptables-services iptables iptables-persistent"
	fi
    $PKG_MGR install acl -y >/dev/null 2>&1
    [[ -n $iptin ]] && for x in $iptin; do $PKG_MGR -y install $x >/dev/null 2>&1;done
    if [[ $OS_TYPE -eq 3 ]];then
        systemctl enable netfilter-persistent.service >/dev/null 2>&1
        systemctl restart netfilter-persistent.service >/dev/null 2>&1
    else
        systemctl start iptables >/dev/null 2>&1
        if [[ $? -eq 0 ]];then
            systemctl start ip6tables >/dev/null 2>&1
            systemctl enable iptables >/dev/null 2>&1
            systemctl enable ip6tables >/dev/null 2>&1
        fi
    fi
    if [[ -n $(which iptables 2>/dev/null) ]];then
        systemctl stop iptables >/dev/null 2>&1
        if [[ $? -eq 0 ]];then
            systemctl start iptables >/dev/null 2>&1
            systemctl enable iptables >/dev/null 2>&1
        fi
    fi
    ssh_port=$(grep '^Port' /etc/ssh/sshd_config | cut -d' ' -f2)
    [[ -z $ssh_port ]] && ssh_port=22
    if [[ -n $(which iptables 2>/dev/null) ]];then
        iptables -F >/dev/null 2>&1
        /sbin/iptables -I INPUT -p tcp --dport $ssh_port -j ACCEPT > /dev/null 2>&1
        /sbin/iptables -I INPUT -p tcp --dport 443  -j ACCEPT >/dev/null 2>&1
        /sbin/iptables -I INPUT -p tcp --dport 80  -j ACCEPT >/dev/null 2>&1
        /sbin/iptables -I INPUT -p tcp --dport 53  -j ACCEPT >/dev/null 2>&1
        /sbin/iptables -I INPUT -p udp --dport 53  -j ACCEPT >/dev/null 2>&1
        # [[ -d "/etc/sysconfig" ]] && iptables-save >/etc/sysconfig/iptables 2>/dev/null
        # [[ -d "/etc/iptables" ]] && iptables-save >/etc/iptables/rules.v4 2>/dev/null
        service iptables save >/dev/null 2>&1
        [[ -e /etc/iptables-conf ]] && cp -p /etc/iptables-conf{,-$(date +%s)}
        if [[ -e "/etc/sysconfig/iptables" ]] || [[ -n $(which yum 2>/dev/null) ]];then
            iptables-save > /etc/sysconfig/iptables 2>/dev/null
        elif [[ -e "/etc/iptables-conf" ]];then
            iptables-save > /etc/iptables-conf 2>/dev/null
        elif [[ -e "/etc/iptables/rules.v4" ]] || [[ -n $(which apt 2>/dev/null) ]];then
            iptables-save > /etc/iptables/rules.v4 2>/dev/null
            invoke-rc.d iptables-persistent save >/dev/null 2>&1
        fi
        service iptables save >/dev/null 2>&1
        if [[ -f /etc/sysconfig/iptables-config ]];then
            sed -i '/IPTABLES_SAVE_ON_RESTART=/c\IPTABLES_SAVE_ON_RESTART="yes"' /etc/sysconfig/iptables-config
            sed -i '/IPTABLES_SAVE_ON_STOP=/c\IPTABLES_SAVE_ON_STOP="yes"' /etc/sysconfig/iptables-config
        fi
    fi
}


notify() {
    type=$1
    txt=$2
    case $type in
        'error')
            echo -e "\n${red}${bold}${txt}${end}\n"
        ;;

        'success')
            echo -e "\n${green}${bold}${txt}${end}\n"
        ;;

        'warning')
            echo -e "\n${yellow}${bold}${txt}${end}\n"
        ;;

        'info')
            echo -e "\n${blue}${bold}${txt}${end}\n"
        ;;
    esac
    sleep 2
}

uninstall_gdns(){
    echo "Removing Application Directory..."
    rm -rvf /var/www/html/* 2>/dev/null
    echo "Removing Dependencies..."
    iptables -F >/dev/null 2>&1
    mysql -e "DROP DATABASE gdns_edge;" >/dev/null 2>&1
    pakgs=("epel-release" "httpd" "mariadb-server" "mariadb-client" "dnsutils")
    $PKG_MGR -y remove 'php-*' 'bind*' '*mailx' 'apache2' 'MariaDB-*' >/dev/null 2>&1
    if [[ $OS_TYPE -eq 3 ]]; then
        apt purge apache2 'php*' 'bind*' 'libapache2-mod-gnu*' -y >/dev/null 2>&1
        apt remove --purge 'libapache2-mod-php7.2' -y >/dev/null 2>&1
        apt remove --purge 'libapache2-mod-gnutls' -y >/dev/null 2>&1
        apt autoremove -y >/dev/null 2>&1
    fi
    for x in ${pakgs[@]};do
        echo "Removing... ${x}"
        $PKG_MGR -y remove "$x" >/dev/null 2>&1
    done
    iptables -F >/dev/null 2>&1
    [[ -d "/etc/sysconfig" ]] && iptables-save >/etc/sysconfig/iptables 2>/dev/null
    [[ -d "/etc/iptables" ]] && iptables-save >/etc/iptables/rules.v4 2>/dev/null
    ( crontab -l 2>/dev/null | grep -v "/var/www/html/artisan" ; ) | crontab -
    echo "gDNS Edge Uninstallation completed."
    ps aux | grep 'mysql\|http\|apache' | grep -v grep | awk '{print $2}' | xargs kill -9 >/dev/null 2>&1
    return 200
}

systemUtilCheck() {
    which crontab >/dev/null 2>&1
    if [[ $? -ne 0 ]]; then
        [[ $OS_TYPE -le 2 ]] && $PKG_MGR install cronie -y >/dev/null 2>&1
        [[ $OS_TYPE -eq 3 ]] && $PKG_MGR install cron -y >/dev/null 2>&1
        if [[ $OS_TYPE -le 2 ]];then
            systemctl enable crond >/dev/null 2>&1
            systemctl start crond >/dev/null 2>&1
        else
            systemctl enable cron >/dev/null 2>&1
            systemctl start cron >/dev/null 2>&1
        fi
    fi
}

PHP74_install(){
# Checking PHP version 
    export php_version="7.4"
    source /etc/os-release
    version=$(echo $VERSION | grep -o '[0-9]*' | head -1)
    [[ -z $version ]] && version=$(rpm -E %{rhel})
    [[ $OS_TYPE -eq 1 ]] && dnf update -y >/dev/null
    PHP_VER=$(php -v  2>/dev/null |  grep --only-matching --perl-regexp "[0-9]\.\\d+"  2>/dev/null |  head -1)
    if [[ -n $PHP_VER ]] && [[ ${PHP_VER//.} -eq 74 ]];then
          echo "PHP 7.4 already installed."
        return 200
    else
        $PKG_MGR remove -y "php*" >/dev/null 2>&1
    fi
    if [[ $OS_TYPE -eq 1 ]];then
        $PKG_MGR -y install httpd >/dev/null 2>&1
        systemctl restart httpd >/dev/null 2>&1
        [[ -z $version ]] && version=8
        $PKG_MGR -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-$version.noarch.rpm >/dev/null 2>&1
        $PKG_MGR module reset php -y >/dev/null 
        $PKG_MGR -y install dnf-utils http://rpms.remirepo.net/enterprise/remi-release-$version.rpm >/dev/null 2>&1
        dnf module enable php:7.4 -y >/dev/null 2>&1
        if [[ $? -gt 0 ]];then
            $PKG_MGR module enable php:remi-$php_version -y >/dev/null 2>&1
            $PKG_MGR module install php:remi-$php_version -y >/dev/null 2>&1
        else
            $PKG_MGR module enable php:7.4 -y >/dev/null
            $PKG_MGR module install php:7.4 -y >/dev/null
        fi
        $PKG_MGR update -y >/dev/null 2>&1
        for x in php php-gd php-mysqlnd php-mysql php-xml php-pear php-gmp php-intl php-curl; do $PKG_MGR install -y $x >/dev/null 2>&1;done
        sleep 0.5
        systemctl restart httpd >/dev/null 2>&1
    elif [[ $OS_TYPE -eq 2 ]];then
        [[ -z $version ]] && version=7
        $PKG_MGR -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-$version.noarch.rpm >/dev/null 2>&1
        $PKG_MGR -y install http://rpms.remirepo.net/enterprise/remi-release-$version.rpm >/dev/null 2>&1
        $PKG_MGR -y install yum-utils >/dev/null 2>&1
        if [[ $(yum-config-manager --enable remi-php74  2>/dev/null |  wc -l) -le 2 ]]; then
            yum-config-manager --enable remi-php72 >/dev/null 2>&1
        fi
        for x in php php-pecl-mcrypt php-gd php-mysqlnd php-mysql php-xml php-pear php-gmp php-intl php-curl;do $PKG_MGR install -y $x >/dev/null 2>&1;done
        sleep 0.5
        if [[ $(httpd -M 2>/dev/null | grep -c "php.*module") -eq 0 ]];then
            so_file=$(find /etc/httpd/modules/ -type f -iname "*php*.so" | tail -1 2>/dev/ull)
            [[ -z $so_file ]] && so_file="/etc/httpd/modules/libphp*.so"
            echo "LoadModule php7_module $so_file
<FilesMatch \.php$>
    SetHandler application/x-httpd-php
</FilesMatch>" > /etc/httpd/conf.modules.d/00-php.conf
        fi
        systemctl restart httpd >/dev/null 2>&1
    elif [[ $OS_TYPE -eq 3 ]];then
        $PKG_MGR update -y >/dev/null 2>&1
        $PKG_MGR upgrade -y >/dev/null 2>&1
        $PKG_MGR install lsb-release ca-certificates apt-transport-https software-properties-common -y >/dev/null 2>&1
        which add-apt-repository >/dev/null 2>&1
        if [[ $? -ne 0 ]]; then
            $PKG_MGR -y install software-properties-common >/dev/null 2>&1
        fi
        which locale-gen >/dev/null 2>&1
        if [[ $? -ne 0 ]]; then
            $PKG_MGR -y install locales >/dev/null 2>&1
        fi
        locale-gen en_US.UTF-8 >/dev/null 2>&1
        export LANG=en_US.UTF-8 2>/dev/null4
        export LC_ALL=en_US.UTF-8 2>/dev/null
        source /etc/os-release
        ID=$(echo $ID | tr A-Z a-z)
        if [[ $ID == debian ]];then
            wget -qO /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
            $PKG_MGR update >/dev/null 2>&1
        else
            add-apt-repository -y ppa:ondrej/php >/dev/null 2>&1
        fi

        $PKG_MGR -y update >/dev/null 2>&1
        $PKG_MGR -y upgrade >/dev/null 2>&1
        phplib=libapache2-mod-php$php_version
        for x in php$php_version $phplib php$php_version-mysqlnd php$php_version-mysql php$php_version-zip php$php_version-xml php$php_version-gmp php$php_version-intl;do $PKG_MGR install -y $x >/dev/null 2>&1;done
        $PKG_MGR install php$php_version libapache2-mod-php$php_version php$php_version-curl -y >/dev/null 2>&1
        # if it is failed to configure php with apache run => apt install php$php_version libapache2-mod-php
        systemctl restart apache2 >/dev/null 2>&1
    fi
    if [[ $OS_TYPE -gt 1 ]];then
        [[ -n $(which update-alternatives 2>/dev/null) ]] && update-alternatives --set php $(which php 2>/dev/null) >/dev/null 2>&1
        [[ ! -x '/usr/bin/php' ]] && [[ -x /usr/bin/php74 ]] && ln -s /usr/bin/php74 /usr/bin/php
        [[ $OS_TYPE -lt 3 ]] && systemctl restart httpd >/dev/null 2>&1 || systemctl restart apache2 >/dev/null 2>&1
    fi
    export PHP=$(php -v 2>/dev/null | grep --only-matching --perl-regexp "[0-9]\.\\d+" 2>/dev/null | head -1)
    if [[ -z $PHP ]] || [[ ${PHP/./} -ne 74 ]];then
        notify error ">> FAILED"
        return 255
    else
        notify success ">> OK"
    fi
}


IONCUBE_install(){
# IonCube installation
    ioncube_check=$(php -m  2>/dev/null |  grep -ic "ioncube" 2>/dev/null)
    PHP_VER=$(php -v 2>/dev/null |  grep --only-matching --perl-regexp "[0-9]\.\\d+" 2>/dev/null |  head -1)
    if [[ $ioncube_check -eq 0 ]];then
        i_name=ioncube_loader_lin_${PHP_VER}_ts.so
        if [[ "$(php -i  2>/dev/null | awk '/Thread*.Safety/{print $NF}')" == "disabled" ]];then
            i_name=ioncube_loader_lin_${PHP_VER}.so
        fi
        export ext_dir=$(php-config --extension-dir 2>/dev/null)
        [[ -z $ext_dir ]] && export ext_dir=$(php -i 2>/dev/null | awk '/extension_dir.*modules/{print $NF}')
        [[ -z $ext_dir ]] && export ext_dir=$(php -i 2>/dev/null | grep '^extension_dir' | sed 's/ /\n/g' | tail -1)

        [[ ! -f $ext_dir/$i_name ]] && wget -qO $ext_dir/$i_name $repo_base/ioncube/$i_name

        ini_check=$(grep -irwl "zend_extension=$ext_dir/modules/$i_name" $(whereis php | sed 's/ /\n/g' | grep 'php.d'))
        if [[ ! -s $ini_check ]]; then
            echo "zend_extension=$ext_dir/$i_name" > $(php --ini | awk '/Scan*.for/{print $NF}')/00-gdns_php.ini
            [[ -d "/etc/php/$PHP_VER/apache2/conf.d/" ]] && echo "zend_extension=$ext_dir/$i_name" > /etc/php/$PHP_VER/apache2/conf.d/00-gdns_php.ini
            [[ -f "/etc/php/$PHP_VER/apache2/php.ini" ]] && echo "zend_extension=$ext_dir/$i_name" >> /etc/php/$PHP_VER/apache2/php.ini
        fi
        ioncube_check=$(php -m 2>/dev/null | grep -ic "ioncube" 2>/dev/null)
        if [[ $ioncube_check -eq 0 ]];then
            echo "ionCube installation failed!"
            rm -f $(php --ini | awk '/Scan*.for/{print $NF}')/00-gdns_php.ini >/dev/null 2>&1
        fi
    fi
    if [[ $OS_TYPE -lt 3 ]]; then
        systemctl stop httpd >/dev/null 2>&1
        systemctl start httpd >/dev/null 2>&1
    else
        systemctl stop apache2 >/dev/null 2>&1
        systemctl start apache2 >/dev/null 2>&1
    fi

}

MYSQL_fpwdreset() {
    local mysql_password=$1
    mysql_status=$(systemctl status mariadb 2>&1 | grep -ic 'found')
    if [[ $mysql_status -gt 0 ]];then
        mariadbservice=mariadb
    else
        mariadbservice=mysql
    fi
    ps aux | grep 'mysql' | grep -v grep | awk '{print $2}' | xargs kill -9 >/dev/null 2>&1
    M_PID=$(mysqld_safe --skip-grant-tables & >/dev/null 2>&1)
    sleep 5
    mysql_update_code=$(mysql -e "UPDATE mysql.user SET Password=PASSWORD('$mysql_password') WHERE User='root';FLUSH PRIVILEGES;" 2>&1 | grep -ic view)
    if [[ $mysql_update_code -gt 0 ]];then
        mysql -e "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('${mysql_password}');"
    fi
    ps aux | grep 'mysql' | grep -v grep | awk '{print $2}' | xargs kill -9 >/dev/null 2>&1
    systemctl stop $mariadbservice >/dev/null 2>&1
    systemctl start $mariadbservice >/dev/null 2>&1
}

MYSQL_install(){
    m_count=0
    which mysql >/dev/null 2>&1
    if [[ $? -eq 0 ]]; then
        m_count=$(mysql -e "show databases;" -ss  2>/dev/null | wc -l)
    fi
    if [[ $m_count -eq 0 ]]; then
        if [[ $OS_TYPE -eq 2 ]]; then
            $PKG_MGR remove mysql-server -y >/dev/null 2>&1
            [[ -e /etc/yum.repos.d/MariaDB.repo ]] && mv /etc/yum.repos.d/MariaDB.repo{,.$(date +%s)} >/dev/null 2>&1
            $PKG_MGR update -y >/dev/null 2>&1
            echo -e "[mariadb]\nname = MariaDB\nbaseurl = http://yum.mariadb.org/10.3/centos7-amd64\ngpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB\ngpgcheck=1" > /etc/yum.repos.d/mariadb.repo
            yum-config-manager --enable mariadb >/dev/null 2>&1
            $PKG_MGR install mariadb-server -y >/dev/null 2>&1
            sleep 0.5
            mysql_status=$(systemctl status mariadb 2>&1 | grep -ic 'found')
            if [[ $mysql_status -eq 0 ]];then
                systemctl stop mariadb >/dev/null 2>&1
                systemctl start mariadb >/dev/null 2>&1
                mariadbservice=mariadb
            else
                systemctl stop mysql >/dev/null 2>&1
                systemctl start mysql >/dev/null 2>&1
                mariadbservice=mysql
            fi
        elif [[ $OS_TYPE -eq 1 ]];then
            $PKG_MGR remove mysql-server -y >/dev/null 2>&1
            $PKG_MGR install mariadb-server -y >/dev/null 2>&1
            sleep 0.5
            mysql_status=$(systemctl status mariadb 2>&1 | grep -ic 'found')
            if [[ $mysql_status -eq 0 ]];then
                systemctl stop mariadb >/dev/null 2>&1
                systemctl start mariadb >/dev/null 2>&1
                mariadbservice=mariadb
            else
                systemctl stop mysql >/dev/null 2>&1
                systemctl start mysql >/dev/null 2>&1
                mariadbservice=mysql
            fi
        else
            $PKG_MGR remove mysql-server -y >/dev/null 2>&1
            $PKG_MGR purge mysql-server -y >/dev/null 2>&1
            $PKG_MGR install mariadb-server mariadb-client -y >/dev/null 2>&1
            mysql_status=$(systemctl status mariadb 2>&1 | grep -ic 'found')
            if [[ $mysql_status -eq 0 ]];then
                systemctl stop mariadb >/dev/null 2>&1
                systemctl start mariadb >/dev/null 2>&1
                mariadbservice=mariadb
            else
                systemctl stop mysql >/dev/null 2>&1
                systemctl start mysql >/dev/null 2>&1
                mariadbservice=mysql
            fi
        fi
        sleep 3
        m_count=$(mysql -e "show databases;" -ss  2>/dev/null | wc -l)
        which mysql >/dev/null 2>&1
        if [[ $? -gt 0 ]]; then
            echo "MySQL installation failed" && return 255
        fi
        systemctl start $mariadbservice >/dev/null 2>&1
        sleep 2
        systemctl enable $mariadbservice >/dev/null 2>&1
    fi
    export mysql_password=$(curl -s ifconfig.me 2>/dev/null | md5sum | base64 | cut -b 1-12)
    tmpfile=mysql_$(date +%s).sql
    # rm -f /root/.my.cnf >/dev/null 2>&1
    # echo -e "[client]\nuser=root\npassword=" > /root/.my.cnf
    echo "USE mysql;
UPDATE mysql.user SET Password=PASSWORD('${mysql_password}') WHERE User='root';
DELETE FROM mysql.user WHERE User='';
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
CREATE TEMPORARY TABLE userupdate AS SELECT * FROM mysql.user WHERE User='root' AND Host='localhost';
UPDATE userupdate SET Host='127.0.0.1';
INSERT IGNORE INTO mysql.user SELECT * FROM userupdate;
UPDATE userupdate SET Host='${HOSTNAME}';
INSERT IGNORE INTO mysql.user SELECT * FROM userupdate;
UPDATE userupdate SET Host='::1';
INSERT IGNORE INTO mysql.user SELECT * FROM userupdate;
FLUSH PRIVILEGES;" >$tmpfile
    mysql_update_code=$(mysql -sfu root <$tmpfile 2>&1 | grep -ic view)
    if [[ $mysql_update_code -gt 0 ]];then
        mysql -e "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('${mysql_password}');"
    fi
    rm -f $tmpfile
    [[ -s "/root/.my.cnf" ]] && $CP -fp /root/.my.cnf{,.$(date +%s)}
    echo -e "[client]\nuser=root\npassword=${mysql_password}" > /root/.my.cnf
    sleep 0.2
    check_grant=$(mysql -e "SHOW GRANTS;"  2>/dev/null |  grep -wc "unix_socket")
    if [[ $check_grant -gt 0 ]]; then
        mysql -e "use mysql;GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '${mysql_password}' WITH GRANT OPTION;FLUSH PRIVILEGES;" 2>/dev/null
    fi
    mysql -e "show databases;" >/dev/null 2>&1
    if [[ $? -ne 0 ]]; then
        MYSQL_fpwdreset "$mysql_password"
    fi
    mysql -e "DROP DATABASE gdns_edge;" >/dev/null 2>&1
    mysql -e "CREATE DATABASE gdns_edge;" >/dev/null 2>&1
    mysql -e "show databases;" >/dev/null 2>&1
    if [[ $? -eq 0 ]]; then
        notify success ">> OK"
    else
        notify error ">> FAILED"
    fi
}


APACHE_install() {
    # Dependency installation
    APACHE_DIR=apache2
    CONF_DIR=${APACHE_DIR}/sites-available
    CONF_FILE=${APACHE_DIR}/apache2.conf
    SSL_CONF=${CONF_DIR}/default-ssl.conf
    if [[ $OS_TYPE -le 2 ]];then
        $PKG_MGR update -y >/dev/null 2>&1
        APACHE_DIR=httpd
        CONF_DIR=${APACHE_DIR}/conf.d
        CONF_FILE=${APACHE_DIR}/conf/httpd.conf
        SSL_CONF=${CONF_DIR}/ssl.conf
        $PKG_MGR install -y yum-utils >/dev/null 2>&1
        for x in httpd mailx;do $PKG_MGR install -y $x >/dev/null 2>&1;done
        sleep 0.2
        systemctl start httpd >/dev/null 2>&1
        systemctl enable httpd >/dev/null 2>&1
        sleep 0.2
        systemctl restart httpd >/dev/null 2>&1
    elif [[ $OS_TYPE -eq 3 ]];then
        $PKG_MGR update -y >/dev/null 2>&1
        $PKG_MGR upgrade -y >/dev/null 2>&1
        DEBIAN_FRONTEND=noninteractive $PKG_MGR install postfix -y >/dev/null 2>&1
        for x in apache2 bsd-mailx;do $PKG_MGR install -y $x >/dev/null 2>&1;done
        sleep 0.2
        systemctl start apache2 >/dev/null 2>&1
        systemctl enable apache2 >/dev/null 2>&1
        sleep 0.2
        $PKG_MGR install apache2 -y >/dev/null 2>&1
        sleep 0.2
        a2enmod rewrite >/dev/null 2>&1
        # a2enmod ssl >/dev/null 2>&1
        # a2enmod headers >/dev/null 2>&1
        # a2ensite default-ssl >/dev/null 2>&1
        systemctl restart apache2 >/dev/null 2>&1
        sleep 1
    fi
    ServerName=$(hostname -f 2>/dev/null)
    [[ -z $ServerName ]] && ServerName=$(hostname 2>/dev/null)
    [[ -z $ServerName ]] && ServerName='localserver.com'
    sed -i '/\/\/#gdns-apache-conf-start/,/\/\/#gdns-apache-conf-end/d' /etc/$CONF_FILE >/dev/null 2>&1
    #apache config
    apache_conf="/etc/$CONF_DIR/edge.conf"
    if [[ -d "/etc/$CONF_DIR" ]]; then
    cat > $apache_conf <<EOF
#gdns-apache-conf-start
<VirtualHost *:80>
ServerName $ServerName
DocumentRoot ${api_docroot}/public
<Directory "${api_docroot}/public">
Options FollowSymLinks
Allowoverride All
Require all granted
</Directory>
</VirtualHost>
#gdns-apache-conf-end
EOF
    else
        notify warning ">> Apache is already installed and configured!"
    fi

    sed -i 's/^Listen 80/Listen 0.0.0.0:80/g' /etc/$CONF_FILE

    if [[ $OS_TYPE -le 2 ]]; then
        service httpd restart >/dev/null 2>&1
    else
        a2ensite edge.conf >/dev/null 2>&1
        service apache2 restart >/dev/null 2>&1
    fi

    sed -i 's/Options.*Indexes/Options/g' /etc/$CONF_FILE >/dev/null 2>&1
    sed -i 's/Options.*Indexes/Options None/g' /etc/$CONF_FILE >/dev/null 2>&1
    sed -i 's/Options.*FollowSymLinks/Options None/g' /etc/$CONF_FILE >/dev/null 2>&1
    apachectl configtest >/dev/null 2>&1
    res="$?"
    if [[ $res -eq 0 ]] && [[ $OS_TYPE -le 2 ]];then
        systemctl restart httpd >/dev/null 2>&1
    elif [[ $res -eq 0 ]] && [[ $OS_TYPE -eq 3 ]];then
        a2enmod headers >/dev/null 2>&1
        a2dissite 000-default.conf >/dev/null 2>&1
        systemctl restart apache2 >/dev/null 2>&1
    else
        notify error ">> Something went wrong on apache configuration!"
    fi
    [[ $res -eq 0 ]] && notify success ">> OK"
    sleep 2
}


setAppPerm() {
    apache_user=$(ps aux | egrep '([a|A]pache|[h|H]ttpd)' | awk '{ print $1}' | uniq | grep -v 'grep\|root' | tail -1)
	[[ -z $apache_user ]] && apache_user="apache"
    mkdir -p $api_docroot/storage/logs
    echo -n '' > $api_docroot/storage/logs/edge-api.log
    find $api_docroot -type f -exec chmod -R 644 {} \; >/dev/null 2>&1
    find $api_docroot -type d -exec chmod -R 755 {} \; >/dev/null 2>&1
    chown -R $apache_user:$apache_user $api_docroot >/dev/null 2>&1
    chmod -R g+s "$api_docroot/storage" >/dev/null 2>&1
    setfacl -R -m u:${apache_user}:rwx "$api_docroot/storage" > /dev/null 2>&1
    setfacl -R -m g:${apache_user}:rwx "$api_docroot/storage" > /dev/null 2>&1
}

CONFIG_setup() {
    #api conf
    sed -i "s/APP_URL=.*/APP_URL=http:\/\/$(hostname)/g" ${api_docroot}/.env >/dev/null 2>&1
    sed -i "s/DB_PASSWORD=.*/DB_PASSWORD=${mysql_password}/g" ${api_docroot}/.env >/dev/null 2>&1
    which timedatectl >/dev/null 2>&1
    if [[ $? -eq 0 ]];then
        t_zone=$(timedatectl | grep -i 'Time Zone' | awk '{print $3}')
        [[ -z $t_zone ]] && t_zone=$(timedatectl list-timezones | grep $(basename $(readlink -f /etc/localtime)) | head -1)
    else
        t_zone=$(readlink -f /etc/localtime | awk -F 'zoneinfo' '{print $2}' | sed 's#^/##g')
    fi
    [[ -z $t_zone ]] && t_zone="UTC"
    sed -i "\#APP_TIMEZONE=#c\APP_TIMEZONE=${t_zone}" ${api_docroot}/.env >/dev/null 2>&1
    which sudo >/dev/null 2>&1
    [[ $? -ne 0 ]] && $PKG_MGR install sudo -y >/dev/null 2>&1
    [[ ! -L /bin/gdnsbin ]] && ln -s /bin/bash /bin/gdnsbin
    apache_user=$(ps aux | egrep '([a|A]pache|[h|H]ttpd)' | awk '{ print $1}' | uniq | grep -v 'grep\|root' | tail -1)
    [[ -z $apache_user ]] && apache_user="apache"
    sed -i '/\/bin\/gdnsbin/d' /etc/sudoers
    echo "$apache_user ALL = (root) NOPASSWD: /bin/gdnsbin,/usr/sbin/rndc" >>/etc/sudoers
    notify success ">> OK"
}


BIND_install(){
    which named >/dev/null 2>&1
    if [[ "$?" -gt 0 ]]; then
        bindUser=named
        if [[ $OS_TYPE -lt 3 ]];then
            rpm -e --nodeps bind bind-utils >/dev/null 2>&1
            [[ -d "/var/named" ]] && rm -rf "/var/named" >/dev/null 2>&1
            rm -f /etc/named.conf* >/dev/null 2>&1
            sleep 5
            $PKG_MGR install bind bind-utils -y >/dev/null 2>&1
            sleep 3
            systemctl stop named >/dev/null 2>&1
            systemctl start named >/dev/null 2>&1
            2>/dev/null</dev/tcp/localhost/53
            if [[ $? -ne 0 ]];then
                sleep 2
                systemctl restart named >/dev/null 2>&1
            fi
            systemctl enable named >/dev/null 2>&1
        elif [[ $OS_TYPE -eq 3 ]];then
            bindUser=bind
            dpkg -P --force-all bind9 bind9utils bind9-doc dnsutils >/dev/null 2>&1
            sleep 0.2
            apt -f install -y >/dev/null 2>&1
            [[ -d "/var/named" ]] && rm -rf "/var/named" >/dev/null 2>&1
            rm -f /etc/named.conf* >/dev/null 2>&1
            apt autoremove -y >/dev/null 2>&1
            sleep 5
            $PKG_MGR install -y bind9 bind9utils bind9-doc dnsutils >/dev/null 2>&1
            sleep 3
            bconf=/etc/bind/named.conf
            sed -i '/directory.*/a recursion no;' "${bconf}.options" >/dev/null 2>&1
            ln -s /var/cache/bind/ /var/named
            systemctl stop bind9 >/dev/null 2>&1
            systemctl start bind9 >/dev/null 2>&1
            2>/dev/null</dev/tcp/localhost/53
            if [[ $? -ne 0 ]];then
                sleep 2
                systemctl restart bind9 >/dev/null 2>&1
            fi
            systemctl enable bind9 >/dev/null 2>&1
            [[ $? -gt 0 ]] && systemctl enable named >/dev/null 2>&1
        fi
    fi
    depth='/var/named'
    [[ -s "/etc/bind/named.conf.local" ]] && depconf="/etc/bind/named.conf.local" || depconf="/etc/named.conf"
    if [[ -e $depconf ]] || [[ -d $depth ]];then
        [[ ! -f "${depconf}.org" ]] && cp -fp $depconf{,.org} >/dev/null 2>&1
        sleep 1
        sed -i '/allow-query/c\allow-query { any; };'  $depconf >/dev/null 2>&1
        sed -i '/recursion/c\recursion no;'  $depconf >/dev/null 2>&1
        sed -i '/listen-on port 53/c\listen-on port 53 { any; };'  $depconf >/dev/null 2>&1
        apache_user=$(ps aux | egrep '([a|A]pache|[h|H]ttpd)' | awk '{ print $1}' | uniq | grep -v 'grep\|root' | tail -1)
        [[ -z $apache_user ]] && apache_user="apache"
        chown -R $bindUser:${apache_user} "$depth" >/dev/null 2>&1
        chmod g+s "$depth" >/dev/null 2>&1
        chmod o-t "$depth" >/dev/null 2>&1
        setfacl -d -m g:${apache_user}:rwx "$depth" >/dev/null 2>&1
        setfacl -d -m u:${apache_user}:rwx "$depth" >/dev/null 2>&1
        chown $bindUser:${apache_user} "$depconf" >/dev/null 2>&1
        chmod g+s "$depconf" >/dev/null 2>&1
        setfacl -m g:${apache_user}:rwx "$depconf" >/dev/null 2>&1
        setfacl -m u:${apache_user}:rwx "$depconf" >/dev/null 2>&1
    fi
    [[ $OS_TYPE -le 2 ]] && systemctl restart named >/dev/null 2>&1 || systemctl restart bind9 >/dev/null 2>&1
    if [[ $? -eq 0 ]]; then
        notify success ">> OK"
    else
        notify error ">> FAILED"
    fi
}


ControllerConf(){
    while (true);do
        echo -e "\n"
        read -p "Enter Controller IP: " cnt_ip
        val_ip=$(echo $cnt_ip | grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")
        if [[ ${val_ip//.} -ne ${cnt_ip//.} ]] || [[ -z $cnt_ip ]];then
            echo "Invalid IP" && continue
        else
            export cnt_ip
            break;
        fi
    done
}

bug_fixes(){
	# MySQL query limit
	mysql -e "SET GLOBAL max_allowed_packet=16*1024*1024;" >/dev/null

	# Unable to start Apache: (28)No space left on device: AH00023: Couldn't create the mutex
	mkdir -p /etc/sysctl.d
    touch "/etc/sysctl.conf"
	touch /etc/sysctl.d/99-zz_apache_semaphores.conf
	chmod 755 /etc/sysctl.d/ /etc/sysctl.d/99-zz_apache_semaphores.conf
	chown root:root /etc/sysctl.d/ /etc/sysctl.d/99-zz_apache_semaphores.conf
	echo -e "kernel.msgmni = 64000\nkernel.sem = 250****256000 32 1024" >/etc/sysctl.d/99-zz_apache_semaphores.conf
	sysctl -p >/dev/null 2>&1
	sleep 0.5
	apache_user=$(ps aux | egrep '([a|A]pache|[h|H]ttpd)' | awk '{ print $1}' | grep -v grep | uniq | grep -v 'grep\|root' | tail -1)
    [[ -z $apache_user ]] && apache_user="apache"
    ipcs -s | tail -n +4 | head -n -1 | tr -s ' ' | cut -d' ' -f2,3 | while read -r id owner; do [[ "$owner" == "$apache_user" ]] && ipcrm -s "$id" >/dev/null 2>&1; done
    sleep 0.5
    for i in `ipcs -s | awk "/${apache_user}/{ next; } {print $2}"`; do (ipcrm -s $i >/dev/null 2>&1); done
    sleep 0.5

	mariadbservice=mysql
	apacheservice=apache2
	if [[ $OS_TYPE -le 2 ]]; then
		mariadbservice=mariadb
		apacheservice=httpd
	fi
	sleep 0.5
	systemctl restart $mariadbservice >/dev/null 2>&1
	sleep 0.5
	systemctl restart $apacheservice >/dev/null 2>&1
	sleep 0.5
}

[[ -d $api_docroot ]] && size=$(du -s $api_docroot | sed 's/[^0-9]//g' 2>/dev/null)
[[ -z $size ]] && size=0
if [[ $size -gt 100 ]];then
    msg="Do you want to uninstall gDNS Edge $version from this server [Y/n] : "
    action=0
else
    msg="Do you want to install gDNS Edge $version on this server [Y/n] : "
    action=1
fi
while true;do
    read -p "$msg" ans
    case $ans in
        y|Y )
            [[ $action -eq 0 ]] && uninstall_gdns
            break
            ;;
        n|N )
            echo "Installation cancelled by user."
            exit 200
            ;;
        * )
            echo "Invalid option!"
            ;;
    esac
done

[[ $action -eq 0 ]] && exit 0

systemUtilCheck
sleep 1
ControllerConf
notify info "[[ Dependecy Installation ]]\n\n"
sleep 1
notify info "1) Setting up Firewall..."
manageFirewall
sleep 1
notify info "2) Installing Apache..."
APACHE_install
sleep 1
wget -qO /root/$pkg "$repo_base/$pkg" >/dev/null 2>&1
sleep 1
tar -xzf /root/$pkg -C /var/www --no-same-owner >/dev/null 2>&1
sleep 1
[[ "$?" -ne 0 ]] || [[ ! -d "$api_docroot/public" ]] && echo "Downloaded package is broken, contact support." && exit 255
## vendor download
wget -qO $api_docroot/edge-vendor.tgz $repo_base/edge-vendor.tgz
tar -xzf $api_docroot/edge-vendor.tgz -C $api_docroot --no-same-owner >/dev/null 2>&1
if [[ $? -gt 0 ]];then
    notify error "Package has corrupted please contact support."
    notify info "\tRollback started..."
    uninstall_gdns
    exit
fi
rm -f $api_docroot/edge-vendor.tgz

if [[ "$OS_TYPE" -eq 3 ]]; then
	systemctl restart apache2 >/dev/null 2>&1
	[[ $? -ne 0 ]] && service apache2 restart >/dev/null 2>&1
else
	systemctl restart httpd >/dev/null 2>&1
	[[ $? -ne 0 ]] && service httpd restart >/dev/null 2>&1
fi

apache_user=$(ps aux | egrep '([a|A]pache|[h|H]ttpd)' | awk '{ print $1}' | uniq | grep -v 'grep\|root' | tail -1)
[[ -z $apache_user ]] && apache_user="apache"
find ${api_docroot} -type f -exec chmod -R 644 {} \; >/dev/null 2>&1
find ${api_docroot} -type d -exec chmod -R 755 {} \; >/dev/null 2>&1
chown -R $apache_user:$apache_user $api_docroot >/dev/null 2>&1
chmod +x ${api_docroot}/artisan
sleep 1
notify info "3) Installing MYSQL..."
#disabel MariaDB repo if existing
maria_db_count=$(yum repolist 2>/dev/null | grep -ic mariadb)
if [[ $maria_db_count -gt 0 ]];then
    yum --disable mariadb update >/dev/null 2>&1
fi
sleep 1
MYSQL_install
notify info "4) Installing PHP..."
sleep 1
PHP74_install
IONCUBE_install
sleep 1
notify info "5) Installing BIND..."
BIND_install
sleep 1
notify info "6) Configuring services..."
sleep 1
setAppPerm
sleep 1
CONFIG_setup
sleep 1
( crontab -l 2>/dev/null | grep -v "/var/www/html/artisan" ; ) | crontab -
sleep 1
PHP_exc=$(which php)
[[ -z $PHP_exc ]] && PHP_exc=php
crontab -l | { cat; echo "* * * * * $PHP_exc /var/www/html/artisan schedule:run  >/dev/null 2>&1"; } | crontab -
$PHP_exc ${api_docroot}/artisan migrate >/dev/null 2>&1
sleep 1
$PHP_exc ${api_docroot}/artisan db:seed --class=edge_settings >/dev/null 2>&1
sleep 1
mysql -e "DELETE FROM gdns_edge.edge_settings WHERE title='controller';" >/dev/null 2>&1
mysql -e "INSERT INTO gdns_edge.edge_settings VALUES(0,'controller','$cnt_ip');" >/dev/null 2>&1
sleep 1
bug_fixes
[[ -e "/etc/httpd/conf.d/welcome.conf" ]] && sed -i.bak 's/^/#/' /etc/httpd/conf.d/welcome.conf
[[ $OS_TYPE -le 2 ]] && systemctl restart httpd >/dev/null 2>&1 || systemctl restart apache >/dev/null 2>&1
chmod -R 0644 $api_docroot/*.php >/dev/null 2>&1
service iptables save >/dev/null 2>&1
notify success "Installation is complete!"
notify warning "Please reboot the server before use!"
rm -f /root/$pkg /root/.dbpasswd