#!/bin/bash
print_red () {
    echo -e "\033[91m"$1"\033[0m"
}
print_red_read () {
    echo -e -n "\033[91m"$1"\033[0m"
    read
}
print_yellow () {
    echo -e "\033[93m"$1"\033[0m"
}
print_yellow_read () {
    echo -e -n "\033[93m"$1"\033[0m"
    read
}
print_green () {
    echo -e "\033[92m"$1"\033[0m"
}
print_green_u () {
    echo -e "\033[92m\033[4m"$1"\033[0m"
}
log () {
    echo "$1" >> $log_filename
}
validate_root_privileges () {
    if [[ $EUID -ne 0 ]]; then
        printf "Root priveleges: "
	print_red NO
	print_yellow "Exiting..."
	exit
    else
        printf "Root priveleges: "
	print_green OK
    fi
}
validate_internet_access () {
    curl ya.ru > /dev/null 2>&1
    if [[ $? -ne 0 ]]; then
        printf "Internet access: "
	print_red NO
    else
        printf "Internet access: "
	print_green OK
    fi
}
validate_license_key () {
#    printf "Enter license key AAAA-BBBB-CCCC-DDDD: "
    print_yellow_read "Enter license key, XXXX-XXXX-XXXX-XXXX: "
    license_key=$REPLY
    command='curl -s --request POST 'https://www.netams.com/cgi/download-wnam.cgi' --data 'key=$REPLY''
#    printf "$(${command})"
    license_token=$(${command} | grep token | sed 's|.*token=||' | sed -r 's/<.+//')
    printf "License key: "
    if [ -z $license_token ]; then
        print_red "$license_key is not valid, exiting..."
	exit
    else
        print_green "OK"
    fi
}
validate_locale () {
    default_ru_locale=$(locale | grep 'LANG=ru_RU.UTF-8')
    printf "Default locale: "
    if [ -z "${default_ru_locale}" ]; then
        print_red $(locale | grep 'LANG=')
    else
        print_green "OK"
    fi
}
validate_system_requirements () {
    clear
    print_green "Validate system requirements selected.\n"
#    log "Validate system requirements selected."
    printf "CPU cores count: "
#    echo "CPU model name: $(lscpu | grep 'Model name:' | cut -d ':' -f2)"
    cores_count=$(nproc)
    if (( cores_count > 1 )); then
        printf "$cores_count "
	print_green "OK"
    else
	print_red "$cores_count - at least 2 CPU cores required!\n"

	print_yellow_read "Proceed installation anyway y/n? "
	read
	if [ "$REPLY" == "n" ]; then
	    print_yellow "Exiting..."
	    exit
	fi
    fi
#    echo -e "Total memory, KB: $(vmstat -s | grep 'total memory' | awk '{ print $1 }')" | tee -a $log_filename
#    echo -e "Total memory, KB: $(free --mega | grep Mem: | awk '{ print $2 }')"
    total_memory=$(free --mega | grep Mem: | awk '{ print $2 }')
    printf "Total memory: "
    if (( $total_memory > 8000 )); then
        printf "$total_memory MB"
	print_green "OK"
    else
	print_red "$total_memory MB - at least 8 GB required!"
	print_yellow_read "Proceed installation anyway y/n? "
	if [ "$REPLY" == "n" ]; then
	    print_red "Exiting..."
	    exit
	fi
    fi
    local var_partition=$(df /var/lib | awk '{print $1}' | tail -n1)
    local space_free=$(df -BM /var/lib | awk '{print $4}' | tail -n1 | sed s/[^0-9]//g)
    printf "/var/lib is on $var_partition, space free: "
    if (( space_free > 40000 )); then
        printf "$space_free MB"
	print_green " OK"
    else
	print_red "$space_free MB - at least 40 GB required!"
	print_yellow_read "Proceed installation anyway y/n? "
	if [ "$REPLY" == "n" ]; then
	    print_red "Exiting..."
	    exit
	fi
    fi
    if [ -z ${OFFLINE} ]; then
        validate_root_privileges
        validate_internet_access
        validate_license_key
    fi
    validate_locale
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS=$NAME
        VER=$VERSION_ID
    fi
    if [[ ("$OS" == *"Debian"* && $VER == "12") || ("$OS" == "Ubuntu" && "$VER" == "22.04") ]]; then
        if [[ -z $(grep -i avx /proc/cpuinfo) ]]; then
            print_red "This system requires use of the AVX CPU instruction set.\nCannot continue the installation!\n"
            exit
        fi
    fi
}
generate_set_RU_locale () {
    print_yellow "\nGenerating ru_RU.UTF-8 locale..."
    locale-gen ru_RU.UTF-8
    print_yellow "\nUpdating default locale..."
    localectl set-locale LANG=ru_RU.UTF-8
}
mongoDB_local_storage_install () {
    clear
    print_green "Installing from local storage selected."
    log "Installing from local storage selected."
#    wget -P $tempdir -m --no-parent http://packages.wnam.ru/mongodb-org/
    apt install $tempdir/packages.wnam.ru/mongodb-org/*.deb
}
install_mongoDB () {
    clear
#    log "Installing from repository selected.";
    if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
    VER=$VERSION_ID
    fi
    if [ -z ${OFFLINE} ]; then
        print_green "Installing from repository selected.\n"
	    apt-get install -y gnupg
        if [[ "$OS" == *"Debian"* ]] && [ $VER == "12" ]; then
            wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | apt-key add -
            echo "deb https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-6.0.list
        elif [ "$OS" == "Ubuntu" ] && [ $VER == "22.04" ]; then
            wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | apt-key add -
            echo "deb https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-6.0.list
        else
            wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | apt-key add -
            #wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
            echo "deb http://repo.mongodb.org/apt/debian buster/mongodb-org/4.4 main" | tee /etc/apt/sources.list.d/mongodb-org-4.4.list
        fi
        apt-get update
        apt-get install -y mongodb-org
    else
        print_green "Installing MongoDB from local packages.\n"
        dpkg -i ./install/packages/mongo/*.deb
    fi
    systemctl enable mongod
    systemctl restart mongod
}
review_mongoDB () {
    clear
    print_green "Review MongoDB selected.";
    log "Review MongoDB selected.";
    print_yellow "\nInspecting gnupg installed:"
    printf "\n"
    dpkg-query -l | grep gnupg
    print_yellow "\nInspecting mongodb installed:"
    printf "\n"
    dpkg-query -l | grep mongodb
    print_yellow "\nInspecting mongod service status:"
    printf "\n"
    systemctl status mongod
}
remove_mongoDB () {
    clear
    print_red "Remove MongoDB selected.";
    log "Remove MongoDB selected.";
    systemctl stop mongod
    apt-get remove --auto-remove mongodb-org
    apt-get purge mongodb-org
    apt-get purge mongodb-org-server
    apt-get purge mongodb-org-mongos
    apt-get purge mongodb-org-shell
    apt-get purge mongodb-database-tools
    apt-get purge mongodb-org-database-tools-extra
}
inspect_web_servers () {
    clear
    print_green "Inspect nginx, apache installation selected.";
    log "Inspect nginx, apache installation selected.";
    print_yellow "\nInspecting nginx service status:"
    printf "\n"
    systemctl status nginx
    print_yellow "\nInspecting /etc/nginx/sites-available/ files:\n"
    ls -l /etc/nginx/sites-available/
    print_yellow "\nInspecting /etc/nginx/sites-enabled/ files:\n"
    ls -l /etc/nginx/sites-enabled/
    print_yellow "\nInspecting apache service status:"
    printf "\n"
    systemctl status apache
}
install_nginx () {
    clear
    print_green "Install nginx selected.\n";
    if systemctl status apache2 | grep running > /dev/null; then
	print_red_read "Running apache2 service detected - stop and disable it y/n? "
	if [ "$REPLY" == "y" ]; then
	    print_yellow "Stopping apache2...\n"
	    systemctl stop apache2
	    print_yellow "Disabling apache2...\n"
	    systemctl disable apache2
	fi
    fi
#    log "Install nginx selected.";
    if [ -z ${OFFLINE} ]; then
        print_yellow "Installing nginx...\n"
        apt-get install -y nginx
        wget -P $tempdir http://www.netams.com/files/wnam/misc/nginx/wnam
        wget -P $tempdir http://www.netams.com/files/wnam/misc/nginx/starting.html
        wget -P $tempdir http://www.netams.com/files/wnam/misc/nginx/wnam-shield-xs.gif
        wget -P $tempdir http://www.netams.com/files/wnam/misc/nginx/favicon.ico
        mkdir /var/www/html/static
        cp $tempdir/starting.html /var/www/html/static/
        cp $tempdir/wnam-shield-xs.gif /var/www/html/static/
        cp $tempdir/favicon.ico /var/www/html/static/
        print_yellow "\nCopying WNAM nginx configuration file...\n"
        cp $tempdir/wnam /etc/nginx/sites-available/
    else
        print_green "Installing nginx from local packages.\n"
        dpkg -i ./install/packages/nginx/*.deb
        print_yellow "\nCopying WNAM nginx configuration file...\n"
        cp ./install/wnam /etc/nginx/sites-available/
    fi
    print_yellow "\nRemoving file /etc/nginx/sites-enabled/default...\n"
    rm /etc/nginx/sites-enabled/*
    print_yellow "\nCreating WNAM configuration file soft link...\n"
    ln -s /etc/nginx/sites-available/wnam /etc/nginx/sites-enabled/wnam
    print_yellow "\nRestarting nginx service...\n"
    systemctl restart nginx
}
remove_nginx () {
    print_red "Remove nginx selected.";
    systemctl stop nginx
    apt-get --purge --auto-remove remove nginx
    apt-get --purge --auto-remove remove nginx-core
    apt-get --purge --auto-remove remove nginx-common
}
install_phantomjs () {
    if [ -z ${OFFLINE} ]; then
        wget -P $tempdir https://www.netams.com/files/wnam/misc/phantomjs-2.1.1-linux-x86_64.tar.bz2
        apt-get install -y bzip2
        tar jxvf ./$tempdir/phantomjs-2.1.1-linux-x86_64.tar.bz2 -C ./$tempdir
        mv ./$tempdir/phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin/phantomjs
        wget -P $tempdir http://www.netams.com/files/wnam/misc/render.js
        mv ./$tempdir/render.js /usr/local/bin/
        wget -P $tempdir http://www.netams.com/files/wnam/misc/render.sh
        mv ./$tempdir/render.sh /usr/local/bin/
    else
        tar jxvf ./install/phantomjs-2.1.1-linux-x86_64.tar.bz2 -C ./install
        mv ./install/phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin/phantomjs
        cp ./install/render.js /usr/local/bin/
        cp ./install/render.sh /usr/local/bin/
    fi
    chmod +x /usr/local/bin/render.sh
    ls -l /usr/local/bin
}
create_kannel_file () {
cat << EOF >> $tempdir/kannel
#START_WAPBOX=1
START_SMSBOX=1
EOF
}
install_asterisk_kannel () {
    if ! [ -z ${OFFLINE} ]; then
	return
    fi
    clear
    print_green "Install asterisk and kannel selected.\n";
    print_yellow "Installing asterisk...\n"
    . /etc/os-release
    OS=$NAME
    VER=$VERSION_ID
    if [[ "$OS" == *"Debian"* ]] && [ $VER == "12" ]; then
        print_red "Asterisk packages is not available on Debian 12"
    else
        apt-get install -y asterisk
    fi
    if [ -f /etc/astra_version ]; then
        print_red "Kannel is not available on Astra Linux\nInstall it manually if needed"
    else
        create_kannel_file
        wget -P $tempdir http://www.netams.com/files/wnam/misc/kannel.conf
        print_yellow "Installing kannel...\n"
        apt-get install -y kannel
        print_yellow "\nCopying kannel configuration file...\n"
        cp $tempdir/kannel.conf /etc/kannel/
        print_yellow "\nCopying kannel file to /etc/kannel/defaults...\n"
        mkdir /etc/kannel/defaults
        cp $tempdir/kannel /etc/kannel/defaults
        print_yellow "\nRestarting kannel service...\n"
        systemctl restart kannel
    fi
}
install_java () {
    print_green "Install Java selected.\n";
    if [ -z ${OFFLINE} ]; then
        if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS=$NAME
        VER=$VERSION_ID
            if [ "$OS" == "Ubuntu" ] && [ $VER == "20.04" ]; then
                java_ver=11
            elif [ "$OS" == "Ubuntu" ] && [ $VER == "22.04" ]; then
                java_ver=11
            elif [[ "$OS" == *"Debian"* ]] && [ $VER == "11" ]; then
                java_ver=11
            elif [[ "$OS" == *"Debian"* ]] && [ $VER == "12" ]; then
                java_ver=17
            elif [ "$OS" == "Astra Linux" ]; then
                java_ver=11
            else
                print_red "Operation system $OS $VER is not supported"
            fi
        fi
        print_yellow "Installing Java from repository...\n"
        apt-get install -y openjdk-${java_ver}-jdk-headless
    else
        print_green "Installing Java from local packages.\n"
        dpkg -i ./install/packages/java/*.deb
        java_ver=11
    fi
    file=/etc/java-${java_ver}-openjdk/security/java.security
    start=$(sed -n '/^jdk.certpath.disabledAlgorithms/=' $file)
    if [ -n $start ]; then
        let end=$start+3
        sed -i "${start},${end}s/^/#/" $file
        start=$(sed -n '/^jdk.tls.disabledAlgorithms/=' $file)
        let end=$start+2
        sed -i "${start},${end}s/^/#/" $file
        sed -i "${end} a jdk.tls.disabledAlgorithms=TLSv1.3" $file
    fi
    print_yellow "\nJava version:\n"
    java -version
}
remove_java () {
    print_green "Remove Java selected.\n";
    print_yellow "Removing Java...\n"
    apt-get --purge --auto-remove remove openjdk-*-jdk
}
create_wnam_nginx_file () {
cat << EOF >> $tempdir/wnam
server {
listen 80;
 access_log /var/log/nginx/access.log;
 location / {
  proxy_pass http://127.0.0.1:8080/;
  proxy_set_header X-Real-IP \$remote_addr;
  proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
  proxy_read_timeout 120;
  proxy_connect_timeout 120;
 }
}
EOF
}
create_wnam_service_file () {
cat << EOF >> $tempdir/wnam.service
[Unit]
Description=WNAM Server

[Service]
WorkingDirectory=/home/wnam
ExecStart=/home/wnam/wnam.war
SuccessExitStatus=143
Restart=on-failure
RestartSec=10
User=wnam
Group=wnam

StandardOutput=append:/home/wnam/logs/console.log
StandardError=append:/home/wnam/logs/console.log

AmbientCapabilities=CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target
EOF
}
# wnam - /etc/nginx/sites-available/
#    wget -O $tempdir/wnam.conf http://www.netams.com/files/wnam/misc/wnam.conf
#    wget -O $tempdir/application.yaml http://www.netams.com/files/wnam/misc/application.yaml
install_wnam_service () {
    print_green "Install WNAM selected.\n";
    mkdir -p /home/wnam/logs
    if [ -z ${OFFLINE} ]; then
        if [ -z $license_token ]; then
		validate_license_key
        fi
        wget -P $tempdir http://www.netams.com/files/wnam/misc/wnam.conf
        mv $tempdir/wnam.conf /home/wnam
        wget -P $tempdir http://www.netams.com/files/wnam/misc/application.yaml
        mv $tempdir/application.yaml /home/wnam
        wget -O $tempdir/wnam.war https://www.netams.com/cgi/download-wnam.cgi?token=$license_token
        #wget -P $tempdir http://www.netams.com/files/wnam/misc/wnam.service
        create_wnam_service_file
        mv $tempdir/wnam.war /home/wnam
        chmod 755 /home/wnam/wnam.war
        mv $tempdir/wnam.service /lib/systemd/system
    else
        cp ./install/wnam.war /home/wnam
        cp ./install/wnam.conf /home/wnam
        cp ./install/application.yaml /home/wnam
        cp ./install/wnam.service /etc/systemd/system
    fi
    useradd -U -s /bin/false wnam
    chown -R wnam:wnam /home/wnam
    systemctl daemon-reload
    systemctl enable wnam
    if [ -z "${default_ru_locale}" ]; then
	generate_set_RU_locale
    fi
    systemctl restart wnam
    printf "\n"
    print_yellow "Waiting until WNAM starts, this may take up to 60 seconds...\n"
    local i=0
    local error=0
    while ! curl -s http://127.0.0.1/login | grep form-signin > /dev/null
    do
	if [[ $i -eq 60 ]]; then
	    print_red "\n\n1 minute timeout exceeded, WNAM authorization page is not available. Exiting..."
	    error=1
	    break
	fi
	printf "."
	sleep 1s
	((i++))
    done
    if [[ $error -eq 0 ]]; then
	printf " $i sec\n"
        if [ -z ${OFFLINE} ]; then
            print_yellow "\nInstalling license key..."
	    curl http://127.0.0.1:8080/api/install_key?key=$license_key
	fi
	print_green "\n\nWNAM authorization page is available at http://$(hostname -I | awk '{print $1}')/wnam/home "
	print_green "\nlogin:admin, password:admin"
    fi
    print_yellow "\nInspecting /home/wnam/logs/ files:\n"
    ls -l /home/wnam/logs/
}
inspect_wnam_installation () {
    clear
    print_green "Inspect WNAM installation selected.\n";
    print_yellow "Inspecting WNAM user created:\n"
    cat /etc/passwd | grep wnam
    print_yellow "\nInspecting WNAM directory created:\n"
    ls -l /home/wnam
    print_yellow "\nInspecting wnam.service file created:\n"
    ls -l /etc/systemd/system | grep wnam
    print_yellow "\nInspecting WNAM service status:\n"
    systemctl status wnam
    print_yellow "\nInspecting WNAM service autostart:\n"
    if ! systemctl status wnam | grep 'wnam.service; enabled;' > /dev/null; then
	print_red "WNAM service autostart disabled."
    else
	print_green "WNAM service autostart enabled."
    fi
    print_yellow "\nInspecting /home/wnam/logs/ files:\n"
    ls -l /home/wnam/logs/
}
remove_wnam_service () {
    clear
    print_green "Remove WNAM selected.\n";
    systemctl stop wnam
    systemctl disable wnam
    rm -R /home/wnam
    rm /etc/systemd/system/wnam.service
}
install_WNAM () {
    print_green "WNAM automatic installation selected.\n"
    validate_system_requirements
    install_mongoDB
    install_java
    install_nginx
    install_phantomjs
    if (whiptail --title "Installation options" --defaultno --yesno "Do you want to install asterisk and kannel?" 10 60) then
        install_asterisk_kannel
    fi
    install_wnam_service
}
create_ADCTool_sudoers_file () {
cat > /etc/sudoers.d/wnam << SUDO
wnam ALL = NOPASSWD: /usr/bin/net
wnam ALL = NOPASSWD: /usr/bin/wbinfo
wnam ALL = NOPASSWD: /usr/bin/systemctl
wnam ALL = NOPASSWD: /usr/bin/ntlm_auth
SUDO
}
create_ADCTool_unit_file () {
cat > /etc/systemd/system/adctool.service << EOF
[Unit]
Description="WNAM Active Directory tools service"
After=network.target

[Service]
WorkingDirectory=/home/wnam/adctool
ExecStart=/usr/local/bin/flask run
Restart=on-failure
SuccessExitStatus=143
RestartSec=10
User=wnam
Group=wnam
StandardOutput=append:/home/wnam/adctool/logs/application.log
StandardError=append:/home/wnam/adctool/logs/console.log

[Install]
WantedBy=multi-user.target

EOF
}
install_ADCTool () {
    useradd -m -U -s /bin/false wnam
    mkdir -p /home/wnam/adctool/logs
    if [ -f /usr/lib/python3.11/EXTERNALLY-MANAGED ]; then
        mv /usr/lib/python3.11/EXTERNALLY-MANAGED /usr/lib/python3.11/EXTERNALLY-MANAGED.old
    fi
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS=$NAME
        VER=$VERSION_ID
    else
        print_red "Operation system is not supported"
        sleep 5
        return
    fi
    if [ -z ${OFFLINE} ]; then
        wget -P $tempdir https://packages.wnam.ru/wnam/1e98eccc-3ab1-4373-95e7-5a2d73a4cab0/adctool.tgz
        tar zxvf $tempdir/adctool.tgz -C /home/wnam
        create_ADCTool_sudoers_file
        create_ADCTool_unit_file
        if [ "$OS" == "Ubuntu" ] && [ $VER == "20.04" ]; then
            apt install -y python3-testresources python3-pip python3-dev python3-gssapi python3-pycryptodome python3-cryptography krb5-user libkrb5-dev winbind python3-werkzeug
            pip3 install python-dotenv
        else
            apt install -y python3-pip python3-gssapi python3-pycryptodome python3-cryptography krb5-user libkrb5-dev winbind python3-werkzeug python3-dotenv
        fi
        #pip3 install -r /home/wnam/adctool/requirements.txt --ignore-installed
        pip3 install -r /home/wnam/adctool/requirements.txt --force-reinstall
    else
        tar zxvf ./install/adctool.tgz -C /home/wnam
        rm /home/wnam/adctool/config.json
        cp ./install/adctool/config.json /home/wnam/adctool
        cp ./install/adctool/wnam /etc/sudoers.d
        dpkg -i ./install/packages/adctool/*.deb
        mv ./install/wheelhouse/pycryptodome-3.16.0.whl ./install/wheelhouse/pycryptodome-3.16.0-cp35-abi3-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl
        pip3 install -r ./install/requirements.txt --no-index --find-links ./install/wheelhouse --ignore-installed
#	pip3 install -r ./install/requirements.txt --no-index --find-links ./install/wheelhouse --force-reinstall
        cp ./install/adctool/adctool.service /etc/systemd/system
    fi
    if [ "$OS" == "Ubuntu" ] && [[ $VER == "20.04" || $VER == "22.04" ]]; then
        if [ ! -f /usr/lib/x86_64-linux-gnu/samba/libwinbind-client.so.0.bak ]; then
            mv /usr/lib/x86_64-linux-gnu/samba/libwinbind-client.so.0 /usr/lib/x86_64-linux-gnu/samba/libwinbind-client.so.0.bak
        fi
        cp /home/wnam/adctool/libwinbind-client.so-ubuntu /usr/lib/x86_64-linux-gnu/samba/libwinbind-client.so.0
    elif [[ "$OS" == *"Debian"* ]] && [ $VER == "11" ]; then
        if [ ! -f /usr/lib/x86_64-linux-gnu/samba/libwinbind-client.so.0.bak ]; then
            mv /usr/lib/x86_64-linux-gnu/samba/libwinbind-client.so.0 /usr/lib/x86_64-linux-gnu/samba/libwinbind-client.so.0.bak
        fi
        cp /home/wnam/adctool/libwinbind-client.so /usr/lib/x86_64-linux-gnu/samba/libwinbind-client.so.0
    elif [[ "$OS" == *"Debian"* ]] && [ $VER == "12" ]; then
        if [ ! -f /usr/lib/x86_64-linux-gnu/libwbclient.so.0.15.bak ]; then
            mv /usr/lib/x86_64-linux-gnu/libwbclient.so.0.15 /usr/lib/x86_64-linux-gnu/libwbclient.so.0.15.bak
        fi
        cp /home/wnam/adctool/libwbclient.so-deb12 /usr/lib/x86_64-linux-gnu/libwbclient.so.0.15
    elif [ "$OS" == "Astra Linux" ]; then
        if [ ! -f /usr/lib/x86_64-linux-gnu/samba/libwinbind-client.so.0.bak ]; then
            mv /usr/lib/x86_64-linux-gnu/samba/libwinbind-client.so.0 /usr/lib/x86_64-linux-gnu/samba/libwinbind-client.so.0.bak
        fi
        cp /home/wnam/adctool/libwinbind-client.so /usr/lib/x86_64-linux-gnu/samba/libwinbind-client.so.0
    else
        print_red "Operation system $OS $VER is not supported"
    fi
    chown -R wnam:wnam /home/wnam
    chmod +x /home/wnam/adctool/*.py
    chmod a+s /usr/bin/wbinfo
    chmod a+s /usr/bin/ntlm_auth
    chown wnam /etc/samba/smb.conf
    if ! grep -q "rdns=false" /etc/krb5.conf
    then
        sed -i '/\[libdefaults\]/a \ \ \ \ \ \ \ \ rdns=false' /etc/krb5.conf
    fi
    systemctl enable adctool
    systemctl start adctool
    systemctl status adctool
    local i=0
    local error=0
    while ! curl -s http://127.0.0.1:9080/is_open | grep adcache > /dev/null
    do
	if [[ $i -eq 5 ]]; then
	    print_red "\n\n5 seconds timeout exceeded, ADCTool is not available. Exiting..."
	    error=1
	    break
	fi
	printf "."
	sleep 1s
	((i++))
    done
    if [[ $error -eq 0 ]]; then
	print_green "\nADCTool started, $i sec"
    fi
}
install_utils () {
    if [ -z ${OFFLINE} ]; then
	apt update
        if ! which curl > /dev/null; then
            print_yellow "\nInstalling curl...\n"
	    apt-get install -y curl
        fi
        if ! which wget > /dev/null; then
            print_yellow "\nInstalling wget...\n"
	    apt-get install -y wget
        fi
        if ! which sudo > /dev/null; then
            print_yellow "\nInstalling sudo...\n"
	    apt-get install -y sudo
        fi
        if ! which whiptail > /dev/null; then
            print_yellow "\nInstalling whiptail...\n"
	    apt-get install -y whiptail
        fi
	if ! which lsof > /dev/null; then
            print_yellow "\nInstalling lsof...\n"
	    apt-get install -y lsof
	fi
        if ! which tcpdump > /dev/null; then
            print_yellow "\nInstalling tcpdump...\n"
	    apt-get install -y tcpdump
        fi
	if ! which nano > /dev/null; then
	    print_yellow "\nInstalling nano...\n"
	    apt-get install -y nano
	fi
    if ! which netstat > /dev/null; then
        print_yellow "\nInstalling net-tools...\n"
        apt-get install -y net-tools
    fi
    else
        print_yellow "Installing utils from local packages...\n"
        dpkg -i ./install/packages/utils/*.deb
    fi
}
create_apt_sources_list () {
cat > /etc/apt/sources.list << APT
deb http://dl.astralinux.ru/astra/stable/1.7_x86-64/repository-main/ 1.7_x86-64 main contrib non-free
deb http://dl.astralinux.ru/astra/stable/1.7_x86-64/repository-update/ 1.7_x86-64 main contrib non-free
deb http://dl.astralinux.ru/astra/stable/1.7_x86-64/repository-base/ 1.7_x86-64 main contrib non-free
deb http://dl.astralinux.ru/astra/stable/1.7_x86-64/repository-extended/ 1.7_x86-64 main contrib non-free
deb http://dl.astralinux.ru/astra/stable/1.7_x86-64/repository-extended/ 1.7_x86-64 astra-ce
APT
}
select_process_installation_steps () {
    while :
	do
#			"1" "Validate system requirements." \
			choice=$(whiptail --title "Installation options" --menu "\nSelect a menu item:" 28 80 16 \
			"2" "Install MongoDB." \
			"22" "Inspect MongoDB installation." \
			"23" "Remove MongoDB." \
			"3" "Install Java." \
			"31" "Remove Java." \
			"4" "Install nginx." \
			"41" "Inspect nginx, apache installation." \
			"42" "Remove nginx." \
			"5" "Install phantomjs." \
			"8" "Install asterisk and kannel." \
			"9" "Install WNAM service." \
			"91" "Inspect WNAM service installation." \
			"92" "Remove WNAM service installation." 3>&1 1>&2 2>&3)
			exitstatus=$?
			if [ $exitstatus = 0 ]; then
				echo "Your chosen option:" $choice
				case $choice in
					"1")	validate_system_requirements;;
					"2")	install_mongoDB;;
#						"21")	mongoDB_local_storage_install;; 
					"22")	review_mongoDB;;
					"23")	remove_mongoDB;;
					"3")	install_java;;
					"31")	remove_java;;
					"4")	install_nginx;;
					"41")	inspect_web_servers;;
					"42")	remove_nginx;;
					"5")	install_phantomjs;;
					"8")	install_asterisk_kannel;;
					"9")	install_wnam_service;;
					"91")	inspect_wnam_installation;;
					"92")	remove_wnam_service;;
				esac
			        print_green "\nPress space to return back."
			        read -n 1
			else
			    return
			fi
	done
}
now=$(date +"%Y-%m-%d-%H-%M")
log_filename="install.$now.log"
tempdir=""
main () {
    clear
#    print_green "$(umask)"
#    read -n 1
    if ! [ -z $1 ]; then
	if [ "$1" = "--offline" ]; then
	    OFFLINE=1
	fi
    else
	if lsb_release -d | grep Astra > /dev/null; then
	    mv /etc/apt/sources.list /etc/apt/sources.list_astra
	    create_apt_sources_list
	fi
    fi
#    rm *.log
#    rm -r ./tmp.*
#    tempdir=$(mktemp -d --tmpdir=./)
    tempdir="./tmp"
    install_utils
while :
    clear
    do
        if [ -z ${OFFLINE} ]; then
	        local choice=$(whiptail --title "ONLINE setup" --menu "\nSelect a menu item:" 18 70 8 \
		"1." "Automatic WNAM installation." \
		"2." "Automatic ADCTool installation." \
		"3." "Installation debug options." 3>&1 1>&2 2>&3)
	        local exitstatus=$?
	        if [ $exitstatus = 0 ]; then
	            echo "Your chosen option:" $choice
                    case $choice in
			"1.")	install_WNAM
				;;
			"2.")	install_ADCTool
				;;
#				"21" "Install MongoDB from local storage." \
			"3.")	select_process_installation_steps
				continue
				;;
		        *)	echo "Exiting..."
				exit 0;;
		esac
		else
                    print_yellow "Exiting..."
		    exit
		fi
	else
	        local choice=$(whiptail --title "OFFLINE setup" --menu "\nSelect a menu item:" 18 70 10 \
		"1." "Astra 1.7.4 automatic OFFLINE WNAM installation." \
		"2." "Astra 1.7.4 automatic OFFLINE ADCTool installation." 3>&1 1>&2 2>&3)
	        local exitstatus=$?
	        if [ $exitstatus = 0 ]; then
	            echo "Your chosen option:" $choice
                case $choice in
			"1.")	install_WNAM
				;;
			"2.")	install_ADCTool
				;;
		        *)	echo "Exiting..."
				exit 0;;
	        esac
    		else
                    print_yellow "Exiting..."
		    exit
	        fi
	fi
        print_green "\nPress space to return back."
        read -n 1
    done
}
main "$@"
