#!/bin/bash

clear_body() {
    tput cup 5 0
    echo -ne "\e[J"
}

if [ -f "/var/brainycp/license" ]; then
  echo -e "\033[1;31m The panel is already installed. Re-installation is detrimental to the system!!!\033[0m\n\n";tput sgr0
  set_error "The panel is already installed!"
  EXIT_ERROR
fi
if [ ! -f "/etc/os-release" ]; then
  echo "Your version OS is not supported! Installation is interrupted!"
  set_error "Your version OS is not supported!"
  EXIT_ERROR
fi
#clear_body

# Get are params of the server
srvosname=`cat /etc/os-release | grep -E '^NAME' | cut -d '=' -f2 | sed 's/\"//g' | xargs`
srvosver=`cat /etc/os-release | grep -E '^VERSION_ID' | cut -d '=' -f2 | sed 's/\"//g' | xargs`
srvname=`hostname`
srvip=`hostname -I`
dip=`ip a s | grep inet | grep dynamic | xargs`
TOTALFILE="/proc/meminfo"
if [ -f $TOTALFILE ]; then
  memtotal=`cat /proc/meminfo | grep MemTotal: | xargs | cut -f2 -d' '`
  swaptotal=`cat /proc/meminfo | grep SwapTotal: | xargs | cut -f2 -d' '`
fi

# Show are params
echo -e "Detected OS Version: \033[1;32m${srvosname} ${srvosver} \033[0m";tput sgr0
echo -e "Detected Server Name: \033[1;32m${srvname} \033[0m";tput sgr0
echo -e "Detected Server IP: \033[1;32m${srvip} \033[0m";tput sgr0
if [ -f $TOTALFILE ]; then
  echo -e "Detected Server RAM memory: \033[1;32m${memtotal} KB\033[0m";tput sgr0
  echo -e "Detected Server SWAP memory: \033[1;32m${swaptotal} KB\033[0m";tput sgr0
fi

# Check redundancy of both RAM and SWAP
sys_err_swap="no"
sys_err_dhcp="no"
# Check RAM
if [ -f $TOTALFILE ]; then
  echo -n "Checking RAM size... "
  if [ "${memtotal}" -ge "900000" ]; then
    echo -en "\033[1;32mPASS \033[0m\n";tput sgr0
  else
    echo -en "\033[1;31mFAIL \033[0m\n";tput sgr0
    echo "There is not enough RAM on your server. A minimum of 900Mb is required. Aborted.";echo ""
    echo "Press any key to continue."
    read -s -n 1
    reset_screen
    exit 1
  fi

# Check SWAP
  echo -n "Checking SWAP size... "
  if [ "${swaptotal}" -ge "2000000" ]; then
    echo -en "\033[1;32mPASS \033[0m\n";tput sgr0
  else
    echo -en "\033[1;31mFAIL \033[0m\n";tput sgr0
    sys_err_swap="yes"
    #echo "There is not enough SWAP on your server. A minimum of 2G is required. Aborted.";echo ""
    #exit -1
  fi
fi

# Check DHCP
echo -n "Checking type IP address... "
if [[ "${dip}" == *"dynamic"* ]];then
  echo -en "\033[1;31mFAIL \033[0m\n";tput sgr0
  sys_err_dhcp="yes"
  #echo "Your IP address is of a dynamic type (DHCP), but you need a static one. Aborted.";echo ""
  #exit 1
else
  echo -en "\033[1;32mPASS \033[0m\n";tput sgr0
fi

#err
if [[ "${sys_err_swap}" == "yes" || "${sys_err_dhcp}" == "yes" ]];then
  echo ""
  echo "The following issues were found:"
fi
if [[ "${sys_err_swap}" == "yes" ]];then
  echo " *) There is not enough SWAP on your server. A minimum of 2G is required."
  echo "    The absence or insufficient volume of this section can lead to unstable operation of the Pael or its services."
fi
if [[ "${sys_err_dhcp}" == "yes" ]];then
  echo " *) Your IP address is of a dynamic type (DHCP), but you need a static one."
  echo "    A dynamic address of a network interface can lead to incorrect operation of some services, "
  echo "    for example, issuing certificates. And also, disrupting the installation process itself."
fi

if [[ "${sys_err_swap}" == "yes" || "${sys_err_dhcp}" == "yes" ]];then
  echo ""
  echo "Please also note that technical support cannot help you until you fix these problems."
fi

if [[ "${sys_err_swap}" == "yes" || "${sys_err_dhcp}" == "yes" ]];then
  echo ""
  tput cnorm
  while true; do
    read -p "Continue installation? {y/n}: " yn
    case $yn in
        [Yy]* )
            echo "Continue and ignore these errors."
            tput civis
            break
            ;;
        [Nn]* )
            set_error "Installation aborted by user"
            #echo "Abort the installation process and exit.";
            sleep 3
            echo "Press any key to continue."
            read -s -n 1
            reset_screen
            exit 1
            ;;
        * ) echo "Please answer yes or no.";;
        esac
    done
fi

##
#
#echo "WARNING!"
#echo "Your system is not supported!"
## echo "Ubuntu 24.x is in the test only. Officially, it is not yet supported. Press any key to continue..."
#echo "Ubuntu 24.x is in the test only. Press any key to continue..."
#echo "Press CTRL+C to abort the installation."
#read -s -n 1

while getopts v:a:s:l:p:-setup::-lang::-package::-version::-action:: option; do
 case "${option}"
 in
        v|--version) VERSION_BUILD=$(echo ${OPTARG} | grep -Eoi '[a-z0-9\.\-]+$');;
        a|--action) ACTION=$(echo ${OPTARG} | grep -Eoi '[a-z0-9\.\-]+$');;
        s|--setup) setup="-s=$(echo ${OPTARG} | grep -E -o '[a-z]+$')";;
	l|--lang) lang="$(echo ${OPTARG} | grep -E -o '[a-z]+$')";;
        p|--package) package="-p=$(echo ${OPTARG} | grep -E -o -i '([a-z0-9\.\-]+,?)+$')";;
 esac
done

if [ $(free | grep Mem: | awk '{print $2}' |grep -Eo '^[0-9]+') -lt "1992294" ]; then
        if [ -z $setup ]; then
                if [ -z $package ]; then
                        setup='-s=min'
                else
                        setup=$package
                fi
        else
                setup=$setup
        fi
else
        if [ -z $setup ]; then
                if [[ -n $package ]]; then
                        setup=$package
                fi
        else
                setup=$setup
        fi
fi

if [[ $(echo $setup |grep -Eo '[a-z]+$') = "min" ]]; then
    echo -e "\n======= Setup minimal configuration ========"
    ## temporare
    if [ "${setup}" == "-s=min" ]; then
        #setup=''
        setup="-p=apache2.4,php56w,php71w,php81w,php85w,imagemagick,certbot,logrotate,MariaDB10.5,phpMyAdmin-5.2.1,exim,pure-ftpd"
    fi
else
    if [ -z $(echo $setup |grep '\-p') ]; then
        echo -e "\n======= The maximum configuration for BrainyCP is selected. ========"
    else
        echo -e "======= Setup \" $(echo $setup |grep -Eoi '([a-z0-9\.\-]+,?)+$')\" ========"
    fi
fi

#echo "+d: $setup"

##############
##
##        Functions prototypes
##

# Function
function get_server_virt_type()
{
    virttypez="$(dmidecode -s system-product-name 2>/dev/stdout| awk '{print $1}')"
    virttypexen="$(dmidecode | grep -i domU 2>/dev/stdout)"
    virttypemic="$(dmidecode | egrep -i 'manufacturer|product' 2>/dev/stdout)"

    if [[ $virttypemic = "Product Name: HVM domU" ]];then
	virttype="microsoftvirtpc"
    elif [[ $virttypexen = "Product Name: HVM domU" ]];then
	virttype="xen"
    elif [[ $virttypez = "/dev/mem:" ]];then
	virttype="openvz"
    elif [[ $virttypez = "KVM" ]];then
	virttype="kvm"
    elif [[ $virttypez = "VMware" ]];then
	virttype="wmware"
    elif [[ $virttypez = "VirtualBox" ]];then
	virttype="virtualbox"
    elif [[ $virttypez = "Bochs" ]];then
	virttype="Bochs"
    else
	virttype="baremetal"
    fi

echo $virttype
}

#function get_ip_server {
#    ipaddr=$(hostname -I)
#    for word in $ipaddr
#     do
#     if [ $word != "127.0.0.1" ];
#     then
#        echo $word
#        break
#     fi
#     done
#}

func_install_package() {
        local result=0
        rm -f install_pkg.log &>/dev/null
        for i in $*; do
                #echo -en "Install package: $i... "
                # apt-get -y install "$i" &>>install_pkg.log
                apt-get install -y "$i" &>>install_pkg.log
                if [ $? -eq 0 ]; then
                        #no error
                        #echo -en "\033[1;32m[OK]\033[0m\n";tput sgr0
                        printf '%-50s \033[0;32mOK\033[0m\n' "Install package: $i... "
                else
                        #error
                        echo -e "\033[1;31mInstall package: $i...  [ERROR]\033[0m\n";tput sgr0
                        result=1
                        break
                fi
        done
        return $result
}

func_prepare() {
	echo -en "\n\nUpdate ruby... "
	gem update --system &>/dev/null
	apt-get install -y libffi-dev  &>install_ruby.log
	gem install fpm &>>install_ruby.log
	echo -en "\033[1;32m [OK] \033[0m\n";tput sgr0
	mkdir -p /run/php-fpm &>/dev/null
	echo 'd /run/php-fpm 755 root root' > /usr/lib/tmpfiles.d/phpx-fpm.conf
}

function valid_ip()
{
    local  ip=$1
    local  stat=1

    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        OIFS=$IFS
        IFS='.'
        ip=($ip)
        IFS=$OIFS
        [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
            && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
        stat=$?
    fi
    return $stat
}

function get_ip_server {
    ip_get=`wget -qO- http://core.brainycp.com/ipchecker.php`
    if valid_ip $ip_get; then
        echo $ip_get
    else
        ipaddr=$(hostname -I)
        for word in $ipaddr
            do
            if [ $word != "127.0.0.1" ]; then
                echo $word
                break
            fi
            done
    fi
}

#	brainy-php5 brainy-php5-modules-base brainy-php5-fpm \
#	brainy-php5-gd brainy-php5-json brainy-php5-pdo brainy-php5-mbstring brainy-php5-mcrypt \
#	brainy-php5-mysql brainy-php5-mbstring brainy-php5-xml \
#	brainy-php5-pgsql brainy-php5-imap brainy-php5-zip brainy-php5-enchant brainy-php5-zendopcache \
#	brainy-php5-imagick brainy-php5-ssh2 brainy-php5-intl \
#	brainy-php5-process \

#######################################
##
##          DATA Segment
##
#######################################
#libmysqlclient16 
package_install=(mysqldb-libs imagemagick liblua5.2-0 libgsasl18 "passwd" \
	"mc" "curl" jailkit \
	brainy-nginx brainy-nginx-all-modules \
	brainy-monitor \
	brainy-ip brainy-core brainy-intro \
	brainy-php8		\
	brainy-php8-bcmath	\
	brainy-php8-cli		\
	brainy-php8-common	\
	brainy-php8-dba		\
	brainy-php8-ffi		\
	brainy-php8-fpm		\
	brainy-php8-gd		\
	brainy-php8-gmp		\
	brainy-php8-imap	\
	brainy-php8-intl	\
	brainy-php8-mbstring	\
	brainy-php8-modules-base \
	brainy-php8-mysql	\
	brainy-php8-pdo		\
	brainy-php8-pgsql	\
	brainy-php8-process	\
	brainy-php8-snmp	\
	brainy-php8-soap	\
	brainy-php8-xml		\
	brainy-php8-zendopcache	\
	brainy-php8-zip		\
	brainy-php8-imagick	\
	brainy-php8-mcrypt	\
	brainy-php8-pear	\
	brainy-php8-ssh2	\
	brainy-php8-xmlrpc	\
	brainy-php8-brcp-tools	\
	brainy-php5 brainy-php5-fpm \
	brainy-connect virt-what ipcalc2 \
	bubblewrap ttyd \
	"openssl" "tar" rclone policykit-1 "whois" \
	libmariadb3 sshpass libpng16-16 logrotate sqlite3 \
	python3-cloudflare python3-certbot-dns-cloudflare iptables \
	lftp zip "unzip" "at" smartmontools ncdu zip)

#####################################
##
##          Main
##
#####################################
#
#  Checking system

#if [[ ! -f "/root/lips.txt" ]];then
#    echo -e "\nERROR: The security key is not found!\n"
#    set_error "The security key is not found!"
#
#    echo "Press any key to continue."
#    read -s -n 1
#    reset_screen
#    exit 1
#fi

echo ""
echo -en "Check of repositories... "
sed -i '/trusted=yes/d' /etc/apt/sources.list  &> /dev/null

echo "http://176.117.78.72/centos/ubuntu24/" | tee /etc/apt/mirrors-u24.txt &> /dev/null
echo "http://repubra.netxi.in/centos/ubuntu24/" | tee -a /etc/apt/mirrors-u24.txt &> /dev/null
echo "http://176.117.78.72/centos/ubuntu24d/" | tee /etc/apt/mirrors-u24d.txt &> /dev/null
echo "http://repubra.netxi.in/centos/ubuntu24d/" | tee -a /etc/apt/mirrors-u24d.txt &> /dev/null
echo "http://176.117.78.72/centos/ubuntu24v8/" | tee /etc/apt/mirrors-u24v8.txt &> /dev/null
echo "http://repubra.netxi.in/centos/ubuntu24v8/" | tee -a /etc/apt/mirrors-u24v8.txt &> /dev/null

#echo "#deb [trusted=yes] http://repubra.netxi.in/centos/ubuntu24/ ubuntu24 main" >> /etc/apt/sources.list
#echo "#deb [trusted=yes] http://repubra.netxi.in/centos/ubuntu24d/ ubuntu24d main" >> /etc/apt/sources.list
#echo "#deb [trusted=yes] http://repubra.netxi.in/centos/ubuntu24v8/ ubuntu24v8 main" >> /etc/apt/sources.list

echo "deb [signed-by=/usr/share/keyrings/brainy-repo.gpg] mirror+file:/etc/apt/mirrors-u24.txt ubuntu24 main" >> /etc/apt/sources.list
echo "deb [signed-by=/usr/share/keyrings/brainy-repo.gpg] mirror+file:/etc/apt/mirrors-u24d.txt ubuntu24d main" >> /etc/apt/sources.list
echo "deb [signed-by=/usr/share/keyrings/brainy-repo.gpg] mirror+file:/etc/apt/mirrors-u24v8.txt ubuntu24v8 main" >> /etc/apt/sources.list

apt-get clean &>/dev/null
#apt-get update &>/dev/null
#DEBIAN_FRONTEND=noninteractive UCF_FORCE_CONFFOLD=1 
apt-get update
if [[ $? -ne 0 ]];then
    echo "error: check of access to a repository failed"
    echo "Press any key to continue."
    read -s -n 1
    reset_screen
    exit 1
else
    echo "pass"
fi

echo ""
echo -e "System update checking, please wait... "
echo -ne '#                         (0%)\r'
apt-get -y remove --purge needrestart &>/dev/null
echo -ne '##                        (3%)\r'
# Set SYSTEMD default
sed -i "/#DefaultMemoryAccounting=/cDefaultMemoryAccounting=yes" /etc/systemd/system.conf &> /dev/null
sed -i "/#DefaultCPUAccounting=/cDefaultCPUAccounting=yes" /etc/systemd/system.conf &> /dev/null
# Set rsyslog default
sed -i "/#cron.*/ccron.*                          /var/log/cron.log" /etc/rsyslog.d/50-default.conf &> /dev/null
echo -ne '##                        (5%)\r'
# Update
apt-get install -y libc &>/dev/null
apt-get install -y kmod &>/dev/null
echo -ne '###                       (11%)\r'
apt-get install -y libssl1.1 &>/dev/null
echo -ne '####                      (18%)\r'
apt-get install -y util-linux &>/dev/null
echo -ne '#####                     (21%)\r'
apt-get install -y python2 &>/dev/null
echo -ne '#######                   (34%)\r'
apt-get install -y python3 &>/dev/null
echo -ne '#########                 (40%)\r'
apt-get install -y apt &>/dev/null
echo -ne '##########                (44%)\r'
apt-get install -y systemd &>/dev/null
echo -ne '#############             (50%)\r'
apt-get install -y perl &>/dev/null
echo -ne '###############           (55%)\r'
apt-get install -y sudo &>/dev/null
echo -ne '################          (62%)\r'
apt-get install -y libc6 &>/dev/null
echo -ne '#####################     (80%)\r'
apt-get -y install snmp-mibs-downloader &>/dev/null
echo -ne '######################    (85%)\r'
apt-get -y install libpam-modules &>/dev/null
apt-get -y remove --purge nullmailer &>/dev/null
apt-get -y remove --purge nginx* node* libnode* php* &>/dev/null
echo -ne '######################    (87%)\r'
#download-mibs

# Remove Shedulers
/bin/systemctl stop atd &>/dev/null
/bin/systemctl stop cron &>/dev/null
apt-get remove --purge -y cron  &>/dev/null
echo -ne '######################### (90%)\r'
apt-get remove --purge -y atd  &>/dev/null
echo -ne '######################### (94%)\r'
apt-get install -y policycoreutils  &>/dev/null
apt-get install -y linux-generic &>/dev/null
apt-get install -y kmod &>/dev/null
echo -ne '##########################(100%)\r'

echo ""
echo -e "\033[1;32m[DONE] \033[0m\n";tput sgr0
# end checked system
####

echo -en "Disable SELINUX...\t"
sleep 2
sed -i "/SELINUX=permissive/cSELINUX=disabled" /etc/selinux/config &> /dev/null
setenforce 0 &> /dev/null
echo -en "\033[1;32m [OK] \033[0m\n";tput sgr0

###
echo ""
echo -en "Update Sheduleer Cron Daemon..."
apt-get install -y cronie &>_system_install.log
if [ $? -eq 0 ]; then
    echo -en "\033[1;32m [OK] \033[0m\n";tput sgr0
else
    echo -e "\033[1;31m [ERROR] \033[0m\n";tput sgr0
    cat _system_install.log
    echo "Press any key to continue."
    read -s -n 1
    reset_screen
    exit 1
fi
PID=`pidof crond`
kill $PID
rm -f /run/cron.* &>/dev/null
rm -f /run/crond.* &>/dev/null
update-rc.d -f cronie remove &>/dev/null
/bin/systemctl restart crond &>/dev/null

get_osname="ubuntu"
get_osver=`cat /etc/debian_version |  grep -Eo '[0-9]' | awk '{print $1}' | head -n1`

#
# Update wget
echo -en "Configure process download... "
apt-get install -y wget &>/dev/null
if [ $? -eq 0 ]; then
    echo -en "\033[1;32m [OK] \033[0m\n";tput sgr0
else
    echo -e "\033[1;31m [ERROR] \033[0m\n";tput sgr0
    echo "Press any key to continue."
    read -s -n 1
    reset_screen
    exit 1
fi
#apt-get update &>/dev/null

#
#  Huge Pages
#
echo -en "Update THP Memory...  "
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag
sysctl -e -w vm.nr_hugepages=20 &>/dev/null
echo "vm.nr_hugepages=20" >> /etc/sysctl.conf
sysctl -p &>/dev/null
apt-get install -y hugepages &>/dev/null
if [ $? -eq 0 ]; then
    echo -en "\033[1;32m [OK] \033[0m\n";tput sgr0
else
    echo -e "\033[1;31m [ERROR] \033[0m\n";tput sgr0
    echo "Press any key to continue."
    read -s -n 1
    reset_screen
    exit 1
fi
systemctl start transparent-huge-pages.service &>/dev/null
#echo -en "\033[1;32m [OK] \033[0m\n";tput sgr0
systemctl enable transparent-huge-pages.service &>/dev/null

##
# Dowload panel
echo -en "Download version... "
wget http://core.brainycp.com/version.txt -P "/tmp/brainyf" &>/dev/null
if download_file "/tmp/brainyf/version.txt" "_system_install.log";then
    echo -en "\033[1;32m [OK] \033[0m\n";tput sgr0
else
    echo -e "\033[1;31m Download version problems... [ERROR] \033[0m\n";tput sgr0
    cat _system_install.log
    echo "Press any key to continue."
    read -s -n 1
    reset_screen
    exit 1
fi

panel_ver=`cat "/tmp/brainyf/version.txt" | awk -F "=" '/current_version/{print $2}'`
rm -f /tmp/brainyf/version.txt

if [ $(printf "%s" "$VERSION_BUILD"|| wc -c) > 1 ]; then
panel_ver=$VERSION_BUILD
else
panel_ver="1.10"
fi

echo -en "Check version $panel_ver... "
check_exist=$(validate_remote_url "latest.tar.gz" "stable/dev_arch/$panel_ver/");
if [ "$check_exist" == "true" ]; then
    echo -e "\033[1;32m [OK] \033[0m"
else
    echo -e "\033[1;31m [NOT FOUND] \033[0m"
    echo "Press any key to continue."
    read -s -n 1
    reset_screen
    exit 1
fi

echo " "
echo -e "Install BrainyCP version $panel_ver for Ubuntu 24.04.x (RC1)\n"
echo $ACTION

# Set date
setdate=$(run_remote_script "date.php")
if [[ $? -eq 0 ]]; then
    date --set="$setdate" &>/dev/null
    #echo "[DEBUG] setdate: ${setdate}"
    echo "Date sync OK"
else
    echo "Date sync FAILED"
    echo "Press any key to continue."
    read -s -n 1
    reset_screen
    exit 1
fi

host=`hostname`
ip_serv=`hostname -I`
#ip_serv=$(get_ip_server)
point=`cat /etc/hosts | grep $(hostname)`
size_point=${#point}
if [ $size_point == 0 ];then
    sed -i "$ a $ip_serv $host" /etc/hosts
fi


###
#
#       main
#
#
echo -e "\n\n\033[1;33m Run Install process\033[0m\n\n";tput sgr0
echo -e "Please wait..."
rm -r -f /tmp/core.brainycp.com/

# Delete the clashing packets
apt-get remove --purge ^exim4-* exim4 -y &>/dev/null
apt-get remove --purge ^apache* apache2 -y &>/dev/null
apt-get remove --purge ^clamav* clamav -y &>/dev/null
apt-get remove --purge ^nginx* nginx -y &>/dev/null
apt-get remove --purge ^mysql* mysql -y &>/dev/null
apt-get remove --purge ^node* libnode* -y &>/dev/null
apt-get remove --purge ^libmariadb* mariadb -y &>/dev/null
apt-get remove --purge ufw -y &>/dev/null
apt-get -y install net-tools &>/dev/null
apt-get -y install quota &>/dev/null

# Install the packages
func_install_package ${package_install[*]}
if [ $? -eq 1 ]; then
        echo -e "An error occurred, see the log file install_pkg.log for details. \n\n"
        tput sgr0
        echo "Press any key to continue."
	read -s -n 1
	reset_screen
        exit 1
fi
mkdir -p /etc/nginx/vhost_logs &>/dev/null
mkdir -p /etc/httpd/vhost_logs/ &>/dev/null
systemctl restart logrotate &>/dev/null

func_prepare

# add users
userpass="$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c8)"
groupadd brainyservice &>/dev/null
useradd  -g  brainyservice -d /dev/null -s /sbin/nologin  brainyservice &>/dev/null
#add no_sshgroup
getent group no_sshgroup >/dev/null || groupadd -g 907 no_sshgroup &>/dev/null
getent passwd no_sshgroup >/dev/null || useradd -u 907 -g no_sshgroup -d /dev/null -s /usr/sbin/nologin no_sshgroup
#groupadd no_sshgroup &>/dev/null
usermod -G no_sshgroup brainyservice &>/dev/null
mkdir -p /var/log/brainyservice &>/dev/null
chown -R brainyservice.brainyservice /var/log/brainyservice  &>/dev/null
mkdir -p /usr/local/brainycp/src/compiled/tmp/brainyservice/ &>/dev/null
chown -R brainyservice.brainyservice /usr/local/brainycp/src/compiled/tmp/brainyservice/ &>/dev/null
useradd mailnull -u 47 -g mail -s /sbin/nologin -d /var/spool/mqueue &>/dev/null
groupadd -r nobody &>/dev/null &>/dev/null
useradd  -g  nobody -d / -s /sbin/nologin  nobody &>/dev/null

#rm -rf  /tmp/brainy/latest.tar.gz
#cp -R -f /tmp/brainy/* /etc/brainy/
#cd /etc/brainy

# Correct openssl 3
sed -i '/\[openssl_init\]/ { N; s/\(providers =[^\n#]*\)/# \1/ }' /etc/ssl/openssl.cnf

set_status "Downloading BrainyCP Panel... "
echo -en "Loading of the installer... "
if download_file "/var/tmp0/brainy/latest.tar.gz" "/var/log/brainy_isp.log" "stable/dev_arch/${panel_ver}/"; then
    echo -en "\033[1;32m [OK] \033[0m\n"; tput sgr0
    set_status "Downloading BrainyCP Panel... [ok]"
else
    echo -e "\033[1;31m [ERROR] \033[0m\n";tput sgr0
    set_error "Download failed: $SRC_FILE"
    echo "There was an error in loading process of the installer."
    cat /var/log/brainy_isp.log
    echo ""
    echo "Press any key to continue."
    read -s -n 1
    reset_screen
    exit 1
fi

set_status "Install BrainyCP Panel... "
echo -en "Install Brainy panel... \t"
cd /var/tmp0/brainy
tar xvf latest.tar.gz &>/var/log/brainy_isp.log
if [ $? -eq 0 ]; then
    echo -en "\033[1;32m [OK] \033[0m\n";tput sgr0
else
    echo -e "\033[1;31m [ERROR] \033[0m\n";tput sgr0
    echo -e "\n\nAn error occurred during the installation panel\n\n"
    echo "Press any key to continue."
    read -s -n 1
    reset_screen
    exit 1
fi

rm -rf  /tmp/brainy/latest.tar.gz
mkdir -p /usr/local/brainycp
/bin/rm -rf  /var/tmp0/brainy/latest.tar.gz
/bin/cp -R -f /var/tmp0/brainy/* /usr/local/brainycp

mkdir -p /etc/brainy
mkdir -p /etc/brainy/tmp
mkdir -p /var/brainycp/data
/bin/cp -R -f /usr/local/brainycp/conf/* /etc/brainy
/bin/cp -R -f /usr/local/brainycp/data/* /var/brainycp/data

/bin/rm -rf  /usr/local/brainycp/conf
/bin/rm -rf  /usr/local/brainycp/data

# PASSWORD
UT=""
ST=""
HT=""
set_status "Install BrainyCP Panel... [ok]"

#while read -r -s line; do
#    if [[ ${HT} == "" ]];then
#        HT=$line
#    elif [[ ${ST} == "" ]];then
#        ST=$line
#    elif [[ ${UT} == "" ]];then
#        UT=$line
#    fi
#done < "/root/lips.txt"

#echo -en "[BETA] Download Brainy panel 8... \t"
#rm -r -f /var/tmp0/brainy
#wget -t3 --http-user=${UT} --http-password="${ST}" ${HT}/brainycp8.zip -P /var/tmp0/brainy &>/var/log/brainy_isp.log
#if [ $? -eq 0 ]; then
#    echo -en "\033[1;32m [OK] \033[0m\n";tput sgr0
#else
#    echo -e "\033[1;31m [ERROR] \033[0m\n";tput sgr0
#    echo -e "\n\nAn error occurred during the installation panel\n\n"
#    echo -e "\n\nMore details /var/log/brainy_isp.log\n\n"
#    echo "Press any key to continue."
#    read -s -n 1
#    reset_screen
#    exit 1
#fi

#echo -en "Install Brainy panel 8... \t"
#cd /var/tmp0/brainy
#tar xvf latest.tar.gz &>/var/log/brainy_isp.log
#unzip -o brainycp8.zip -d /  &>/var/log/brainy_isp.log
#if [ $? -eq 0 ]; then
#    echo -en "\033[1;32m [OK] \033[0m\n";tput sgr0
#else
#    echo -e "\033[1;31m [ERROR] \033[0m\n";tput sgr0
#    echo -e "\n\nAn error occurred during the installation panel\n\n"
#    echo "Press any key to continue."
#    read -s -n 1
#    reset_screen
#    exit 1
#fi

#cd /etc/brainy

host_key_algorithms="ssh-rsa,ssh-dss,ssh-ed25519-cert-v01@openssh.com,ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,sk-ecdsa-sha2-nistp256-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-ed25519,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,sk-ssh-ed25519@openssh.com,sk-ecdsa-sha2-nistp256@openssh.com,rsa-sha2-512,rsa-sha2-256"
pubkey_accepted_algorithms="ssh-rsa,ssh-dss,ssh-ed25519-cert-v01@openssh.com,ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,sk-ecdsa-sha2-nistp256-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-ed25519,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,sk-ssh-ed25519@openssh.com,sk-ecdsa-sha2-nistp256@openssh.com,rsa-sha2-512,rsa-sha2-256"

config_file="/etc/ssh/sshd_config1"

if [ -f "$config_file" ]; then
	if grep -q "^HostKeyAlgorithms" "$config_file"; then
    current_algorithms=$(grep "^HostKeyAlgorithms" "$config_file" | cut -d " " -f 2-)

    for alg in $(echo $host_key_algorithms | tr "," "\n"); do
        if [[ ! "$current_algorithms" =~ "$alg" ]]; then
            current_algorithms="$current_algorithms,$alg"
        fi
    done

    sed -i "s/^HostKeyAlgorithms.*/HostKeyAlgorithms $current_algorithms/" "$config_file"
	else
		echo "" >> "$config_file"
		echo "HostKeyAlgorithms $host_key_algorithms" >> "$config_file"
	fi
	
	if grep -q "^PubkeyAcceptedAlgorithms" "$config_file"; then
    current_algorithms=$(grep "^PubkeyAcceptedAlgorithms" "$config_file" | cut -d " " -f 2-)

    for alg in $(echo $pubkey_accepted_algorithms | tr "," "\n"); do
        if [[ ! "$current_algorithms" =~ "$alg" ]]; then
            current_algorithms="$current_algorithms,$alg"
        fi
    done

    sed -i "s/^PubkeyAcceptedAlgorithms.*/PubkeyAcceptedAlgorithms $current_algorithms/" "$config_file"
	else
		echo "" >> "$config_file"
		echo "PubkeyAcceptedAlgorithms $pubkey_accepted_algorithms" >> "$config_file"
	fi
fi
cd /etc/brainy

echo -en "Updating a configuration of a panel.... "
arch_ver="x86_64"
upd_to="\$GLOBALS['OS_VERSION'] = \"$get_osname$get_osver\";"
sed -i "/OS_VERSION/c$upd_to" /etc/brainy/globals.php
upd_arch="\$GLOBALS['ARCH_VERSION'] = \"$arch_ver\";"
sed -i "/ARCH_VERSION/c$upd_arch" /etc/brainy/globals.php

os_release="\$GLOBALS['OS_RELEASE'] = \"24\";"
sed -i "/OS_RELEASE/c$os_release" /etc/brainy/globals.php
#if [ $arch_ver == 'x86_64' ];then
#upd_dir="\$GLOBALS['LIB_DIR'] = \"lib64\";"
#else
upd_dir="\$GLOBALS['LIB_DIR'] = \"lib\";"
#fi
sed -i "/LIB_DIR/c$upd_dir" /etc/brainy/globals.php

upd_smarty="\$GLOBALS['SMARTY_PATH'] = \"/usr/local/brainycp/lib/smarty-master/libs/Smarty.class.php\";"
sed -i "/SMARTY_PATH/c$upd_smarty" /etc/brainy/globals.php
upd_api="\$GLOBALS['API_PHP_PATH'] = \"/usr/local/brainycp/src/compiled/php8/bin/php\";"
sed -i "/API_PHP_PATH/c$upd_api" /etc/brainy/globals.php

target_file="/etc/brainy/globals.php"
upd_vhost="\$GLOBALS['PHP_TYPE_NEW_STYLE'] = \"on\";"
if grep -q "PHP_TYPE_NEW_STYLE" "$target_file"; then
    sed -i "/PHP_TYPE_NEW_STYLE/c$upd_vhost" "$target_file"
else
    sed -i "/?>/i $upd_vhost" "$target_file" 2>/dev/null || echo -e "\n$upd_vhost" >> "$target_file"
fi

#read -p "Press Enter to continue..."

# Configure or run Web services
sed -i "/memory_limit = 128M/c\memory_limit = 2048M" /usr/local/brainycp/src/compiled/php8/php.ini
chmod 755  /usr/local/brainycp/src/awstats/awstats.pl
#ip_serv=$(ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}' | head -1)
echo -e "[done]"

## IP control
ip_serv=$(get_ip_server)
#sed -i "s/#server_addr#/$ip_serv/g" /usr/local/brainycp/tpl/server_control/default.html
cp /usr/local/brainycp/tpl/basic/server_control/default.html /usr/local/brainycp/tpl/basic/server_control/default1.html
sed -i "s/#server_addr#/$ip_serv/g" /usr/local/brainycp/tpl/basic/server_control/default.html
sed -i "s/#server_addr#/$ip_serv/g" /usr/local/brainycp/nolicense.php

mkdir -p /var/www/html
/bin/rm -rf /var/www/html/default.html
/bin/cp -f /usr/local/brainycp/tpl/basic/server_control/default.html /var/www/html/index.html

ip_dev=`ip route get 1 | awk '{print $NF;exit}' | xargs`
if [[ "$ip_dev" == 192.168.* ]] || [[ "$ip_dev" == 10.* ]];then
        echo '<!-- NATBRAINY -->' >> /var/www/html/index.html
fi


###########################################
##
##                Finish installed
##
#########################
printf "\nBrainyCP installation proccess is finished. Now it will install necessary server software.\n"

# Fix for python3
ln -s /usr/bin/python3 /usr/bin/python

set_status "Starting services... "
#echo -en "\nStarting Brainy SAPI-5... "
#systemctl restart brainyphp-fpm
#if [ $? -eq 0 ]; then
#    echo -en "\033[1;32m [OK] \033[0m\n";tput sgr0
#else
#    echo -e "\033[1;31m [ERROR] \033[0m\n";tput sgr0
#    echo "Press any key to continue."
#    read -s -n 1
#    reset_screen
#    exit 1
#fi
systemctl stop brainyphp-fpm &>/dev/null
systemctl disable brainyphp-fpm  &>/dev/null

echo -en "\nStarting Brainy SAPI-8... "
rm -rf /usr/local/brainycp/tpl/basic/tpl_c/*
sleep 1
systemctl restart brainyphp8-fpm
if [ $? -eq 0 ]; then
    echo -en "\033[1;32m [OK] \033[0m\n";tput sgr0
else
    echo -e "\033[1;31m [ERROR] \033[0m\n";tput sgr0
    echo "Press any key to continue."
    read -s -n 1
    reset_screen
    exit 1
fi
systemctl enable brainyphp8-fpm  &>/dev/null

echo -en "\nStarting Brainy Web Server... "
systemctl restart nginxb
if [ $? -eq 0 ]; then
    echo -en "\033[1;32m [OK] \033[0m\n";tput sgr0
else
    echo -e "\033[1;31m [ERROR] \033[0m\n";tput sgr0
    echo "Press any key to continue."
    read -s -n 1
    reset_screen
    exit 1
fi
systemctl enable nginxb  &>/dev/null

# Restart the brainy-connect service
systemctl restart brainy-socket.service
systemctl enable brainy-socket.service &>/dev/null
systemctl enable brainyip.service &>/dev/null

# Restart the brainy-monitor
mkdir -p /var/brainycp/data/cache/average &>/dev/null
systemctl restart brainy-monitor.timer
systemctl enable brainy-monitor.timer &>/dev/null
set_status "Starting services [ok]"

lang_install=""
if [ -d "/usr/local/brainycp/langs/$lang/" -a -n "$lang" ];then
	lang_install="-l=$lang"
else	
	if [ -n "$default_lang" ];then
		lang_install="-l=$default_lang"
	fi
fi

license_type=""
if [ -n "$default_license" ];then
	license_type="-t=$default_license"
fi
ip_serv_license=""
if [ -n "$ip_serv" ];then
	ip_serv_license="-i=$ip_serv"
fi

/usr/local/brainycp/src/compiled/php8/bin/php /usr/local/brainycp/scripts/setting.php $lang_install $ip_serv_license $license_type &>/dev/null
/usr/local/brainycp/src/compiled/php8/bin/php /usr/local/brainycp/ssh/fstab2.php &>/var/log/brainy_fstab.log

#echo "Configure BRAINY_HTTPD server... "
sqlpass="$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c14)"

echo -e "\n\033[1;33mUpdate config Brainy \033[0m\n";tput sgr0
upd_to="\$GLOBALS['OS_VERSION'] = \"$get_osname$get_osver\";"
sed -i "/OS_VERSION/c$upd_to" /etc/brainy/globals.php
upd_to="\$GLOBALS['LIB_DIR'] = \"lib\";"
sed -i "/LIB_DIR/c$upd_to" /etc/brainy/globals.php
upd_to="\$GLOBALS['ARCH_VERSION'] = \"x86_64\";"
sed -i "/ARCH_VERSION/c$upd_to" /etc/brainy/globals.php

sed -i "/memory_limit = 128M/c\memory_limit = 512M" /usr/local/brainycp/src/compiled/php8/php.ini

echo -en "Determing virtualization type... "
vvirttype="$(get_server_virt_type)"
updd_to="\$GLOBALS['VIRT_TYPE'] = \"$vvirttype\";"
sed -i "/VIRT_TYPE/c$updd_to" /etc/brainy/globals.php
echo -en "\033[1;32m [$vvirttype] \033[0m\n";tput sgr0

/bin/brainysqladmin -u root password "$sqlpass" &>>/var/log/install_brainysql.log

#echo "" >> /etc/brainy/conf/brainy.ini
#echo "[brainy_mysql]" >> /etc/brainy/conf/brainy.ini
#echo "root_password=$sqlpass" >> /etc/brainy/conf/brainy.ini

#FIXME: ??
#chmod 755  /etc/brainy/src/awstats/awstats.pl


############
#######
#
# ip_serv=$(ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}' | head -1)
#ip_serv=$(get_ip_server)
#sed -i "s/#server_addr#/$ip_serv/g" /etc/brainy/tpl/server_control/default.html
#mkdir -p /var/www/html
#rm -rf /var/www/html/default.html
#ln -s /etc/brainy/tpl/server_control/default.html /var/www/html/index.html


#echo -en "Configure BIND... "
#apt-get remove --purge dnsutils bind9-host -y &>/dev/null
#if [ $? -eq 0 ]; then
#        echo -en "\033[1;32m [OK] \033[0m\n"
#        tput sgr0
#else
#        echo -e "\033[1;31m [ERROR] \033[0m\n"
#        tput sgr0
#	exit
#fi

#ln -fs /usr/sbin/service /sbin/service

set_status "Downloading postinstall script... "
echo -en "Loading of the installer... "
if download_file "_fo.sh" "_core_loader.log"; then
    echo -en "\033[1;32m [OK] \033[0m\n";tput sgr0
    set_status "Downloading postinstall script... [ok]"
else
    echo -e "\033[1;31m [ERROR] \033[0m\n";tput sgr0
    set_error "Download failed: $SRC_FILE"
    echo "There was an error in loading process of the installer."
    cat _core_loader.log
    echo ""
    echo "Press any key to continue."
    read -s -n 1
    reset_screen
    exit 1
fi

mkdir -p /var/log/brainy &>/dev/null
/usr/bin/rm -f /root/lips.txt  &>/dev/null
##################
#
#	POSTINSTALL
#
#sed -i "1s/^/127.0.0.1 localhost \n/" /etc/hosts
sed -i "0,/localhost/ i 127.0.0.1 localhost" /etc/hosts

# if [ ! -z "${setup}" ]; then
    # setup=${setup//=/ }
# fi

# run control process
/usr/bin/cp -f /usr/local/brainycp/src/third_party/roundcube/main_pkg8 /etc/brainy/packet_manager/roundcube/main

# run postinstall
d=$(dirname $0)
FILE="/usr/local/brainycp/scripts/postinstall_1.sh"
if [ -f $FILE ];then
#echo "+d: $setup"
    echo -en "\n\033[1;33mRun postinstall process. Please wait...\033[0m\n";tput sgr0
    bash /usr/local/brainycp/scripts/postinstall_1.sh $setup
    if [ $? -eq 0 ]; then
        echo -en "\n\033[1;32mProcess: [DONE] \033[0m\n"
        tput sgr0
    else
	echo -e "\033[1;31m [ERROR] \033[0m\n"
	tput sgr0
	echo "Press any key to continue."
	read -s -n 1
	reset_screen
        exit 1
    fi
fi

# Configure MIBS
download-mibs &>/dev/null

##
## Kernel update params
##
echo -e "\n\n\033[1;33mKernel Update values \n\033[0m\n";tput sgr0

# Set Level 1
#
echo -en "Set for Level 1 of 3...  "

sysctl -e -w fs.file-max=1386242 &>/dev/null
echo "fs.file-max=1386242" >> /etc/sysctl.conf

sysctl -e -w net.ipv4.tcp_max_tw_buckets=265000 &>/dev/null
echo "net.ipv4.tcp_max_tw_buckets=265000" >> /etc/sysctl.conf
#sysctl -e -w net.ipv4.tcp_max_tw_buckets=65000 &>/dev/null
#echo "net.ipv4.tcp_max_tw_buckets=65000" >> /etc/sysctl.conf

sysctl -e -w net.ipv4.tcp_max_syn_backlog=32768 &>/dev/null
echo "net.ipv4.tcp_max_syn_backlog=32768" >> /etc/sysctl.conf

sysctl -e -w net.core.netdev_max_backlog=4096 &>/dev/null
echo "net.core.netdev_max_backlog=4096" >> /etc/sysctl.conf

sysctl -e -w net.core.somaxconn=4096 &>/dev/null
echo "net.core.somaxconn=4096" >> /etc/sysctl.conf

sysctl -e -w net.ipv4.tcp_keepalive_time=300 &>/dev/null
echo "net.ipv4.tcp_keepalive_time=300" >> /etc/sysctl.conf

sysctl -e -w net.ipv4.tcp_fin_timeout=10 &>/dev/null
echo "net.ipv4.tcp_fin_timeout=10" >> /etc/sysctl.conf

sysctl -e -w net.ipv4.tcp_syn_retries=3 &>/dev/null
echo "net.ipv4.tcp_syn_retries=3" >> /etc/sysctl.conf

sysctl -e -w net.ipv4.tcp_synack_retries=3 &>/dev/null
echo "net.ipv4.tcp_synack_retries=3" >> /etc/sysctl.conf

echo -en "\033[1;32m [DONE] \033[0m\n";tput sgr0

# Set Level 2
#
echo -en "Set for Level 2 of 3...  "

# BBR congestion control algorithm (default: cubic)
#sysctl -e -w net.ipv4.tcp_congestion_control=bbr &>/dev/null
#echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf

# BBR requires fq for queue management (default: fq_codel)
#sysctl -e -w net.core.default_qdisc=fq &>/dev/null
#echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf

# Disable the gradual speed increase,  useful on variable-speed WANs but not for us (default: 1)
sysctl -e -w net.ipv4.tcp_slow_start_after_idle=0 &>/dev/null
echo "net.ipv4.tcp_slow_start_after_idle=0" >> /etc/sysctl.conf

# Don't cache ssthresh from previous connection (default: 0)
sysctl -e -w net.ipv4.tcp_no_metrics_save=1 &>/dev/null
echo "net.ipv4.tcp_no_metrics_save=1" >> /etc/sysctl.conf

# Avoid MTU black holes (default: 0)
sysctl -e -w net.ipv4.tcp_mtu_probing=1 &>/dev/null
echo "net.ipv4.tcp_mtu_probing=1" >> /etc/sysctl.conf

echo -en "\033[1;32m [DONE] \033[0m\n";tput sgr0

# Level 3
#
echo -en "Set for Level 3 of 3...  "

sysctl -e -w net.ipv4.ip_nonlocal_bind=1 &>/dev/null
echo "net.ipv4.ip_nonlocal_bind=1" >> /etc/sysctl.conf

sysctl -e -w net.ipv6.ip_nonlocal_bind=1 &>/dev/null
echo "net.ipv6.ip_nonlocal_bind=1" >> /etc/sysctl.conf

# swap
sysctl -e -w vm.swappiness=50 &>/dev/null
echo "vm.swappiness=50" >> /etc/sysctl.conf

# oom_killer disable
sysctl -e -w vm.oom_kill_allocating_task=1 &>/dev/null
echo "vm.oom_kill_allocating_task=1" >> /etc/sysctl.conf

echo "ip6table_filter" >> /etc/modules


#sysctl -e -w kernel.watchdog_thresh=20 &>/dev/null
#echo "kernel.watchdog_thresh=20" >> /etc/sysctl.conf

echo -en "\033[1;32m [DONE] \033[0m\n";tput sgr0

# Check SAPI server
if [[ ! -f "/usr/sbin/nginxb" ]]; then
    echo "ERROR: the brainy-nginx not found!"
    echo "Press any key to continue."
    read -s -n 1
    reset_screen
    exit 1
fi

echo -en "Check of a configuration of the SAPI server... ";tput sgr0
/usr/sbin/nginxb -t &>/dev/null
if [[ $? -eq 1 ]]; then
  echo -e "\033[1;31m[ERROR: check failed]\033[0m\n";tput sgr0
  echo "Press any key to continue."
  read -s -n 1
  reset_screen
  exit 1
else
  echo -e "\033[1;32m[pass]\033[0m\n";tput sgr0
fi

systemctl stop phpsessionclean.timer &>/dev/null
systemctl disable phpsessionclean.timer &>/dev/null
systemctl mask phpsessionclean.timer &>/dev/null
rm -f /etc/apt/apt.conf.d/20packagekit  &>/dev/null

# Add Key
head -c 32 /dev/urandom | base64 > /etc/brainy/br_crypt.key
chown root:root /etc/brainy/br_crypt.key && chmod 600 /etc/brainy/br_crypt.key

# 
echo -e "\n\n\033[1;34m BrainyCP was successfully installed! \033[0m\n\n";tput sgr0
echo -e "\nBy using this product you completely accept License Agreement - https://brainycp.com/license_agreement\n"
echo -e "To use it:\n"
echo -e "http://"$ip_serv":8002 or https://"$ip_serv":8000\n"
echo -e "username: root\n"
echo -e "password: YOUR ROOT PASSWORD\n"
echo ""
echo -e "\033[1;31m 1) WARNING!!! System updated successfully. Please, reboot your system! \033[0m\n";tput sgr0

# FIXME: exit/return
brainy-core -s auto &>_brainy_core_utils.log
#apt-get -y install zip &>/dev/null
chmod 0750 /usr/local/brainycp/ssh/*.php
chmod 0750 /usr/local/brainycp/ssh/*.sh

# quota
config_fstab_quota
init_quota

welcom_screen
sleep 1
#echo "Press any key to continue."
#read -s -n 1
reset_screen
echo "10.1" > /root/version_brainy.txt
brainy_intro -i ${ip_serv}
exit 0

