#!/bin/bash

#############################################
#    USAGE:
#         sudo bash installHES [otpions]
#    or make this file executable:
#         chmode +x installHES
#    and run it:
#         sudo ./installHES [otpions]
#############################################
USAGE=`cat << EOF
usage: 
installHES.sh [otpions]
where  otpions is:
--provider  <database_provider>        type of database provider (MySql or MsSql) default MySql
--hes_dir   <path_to_hes>  path to HES directory. Default /opt/HES
--logfile   <path_to_logfile>  path to log file. Default no log
--url       url for install HES. Default  https://update.hideez.com/hes/linux_x64_latest.tar.gz
--domain_name
--database_user
--database_name
--hes_service
--use_mysql_root_password 
--mysql_root_password
--use_mysql_user_password
--run_wizard
--config_nginx
--hes_port
--from_template
--template_dir
EOF
`

PROVIDER="MySql"
LOGFILE="/dev/null"
HES_URL="https://update.hideez.com/hes/linux_x64_latest.tar.gz"
HESSERVICE="HES"
HES_DIR="/opt/HES"
USE_MYSQL_ROOT_PASSWORD="1"
USE_MYSQL_USER_PASSWORD="1"
RUN_WIZARD="1"
CONFIG_NGINX="1"
HES_PORT="5000"
FROM_TEMPLATE="0"
TEMPLATE_DIR="/opt/HES"
MYSQL_ROOT_PASSWORD=""
SMTP_HOST=""
SMTP_PORT=25
ENABLESSL="true"
SMTP_USER_NAME=""
SMTP_PASSWORD=""
ADD_RECORDS_TO_BASE="0"
CERTTHUMBPRINT="" 
HIDEEZCLOUD="true"
RESTART_HES="0"
APP_TOKEN=""
USER_NAME=""
USER_EMAIL=""
USER_PASSWORD=""


while [ -n "$1" ]
do
        if [ -z "$2" ]  
        then
                echo "ERROR! no values specified after "$1" !" | tee -a $LOG_FILE
                echo "$USAGE"
                exit 1
        fi
        param="$2"

        case "$1" in
                --provider)
                        PROVIDER=$param
                        shift ;;
                --hes_dir)
                        HES_DIR=$param
                        shift ;;
                --logfile)
                        LOGFILE=$param
                        shift ;;
                --url)
                        HES_URL=$param
                        shift ;;
                --urlLogin)
                        URL_LOGIN=$param
                        shift ;;
                --urlPassword)
                        URL_PASSWORD=$param
                        shift ;;
                --domain_name)
                        DOMAIN_NAME=$param
                        shift ;;
                --database_user)
                        DATABASE_USER=$param
                        shift ;;
                --database_name)
                        DATABASE_NAME=$param
                        shift ;;
                --hes_service)
                        HESSERVICE=$param
                        shift ;;
                --use_mysql_root_password)
                        USE_MYSQL_ROOT_PASSWORD=$param
                        shift ;;
                --mysql_root_password)
                        MYSQL_ROOT_PASSWORD=$param
                        shift ;;
                --use_mysql_user_password)
                        USE_MYSQL_USER_PASSWORD=$param
                        shift ;;
                --run_wizard)
                        RUN_WIZARD=$param
                                shift ;;
                --config_nginx)
                        CONFIG_NGINX=$param
                                shift ;;
                --hes_port)
                        HES_PORT=$param
                                shift ;;
                --from_template)
                        FROM_TEMPLATE=$param
                                shift ;;
                --template_dir)
                        TEMPLATE_DIR=$param
                                shift ;;
                --smtp_host)
                        SMTP_HOST=$param
                        shift ;;
                --smtp_port)
                        SMTP_PORT=$param
                        shift ;;
                --enablessl)
                        ENABLESSL=$param
                        shift ;;
                --smtp_user_name)
                        SMTP_USER_NAME=$param
                        shift ;;
                --smtp_password)
                        SMTP_PASSWORD=$param
                        shift ;;
                --add_records_to_base)
                        ADD_RECORDS_TO_BASE=$param
                        shift ;;
                --certthumbprint)
                        CERTTHUMBPRINT=$param
                        shift ;;
                --hideezcloud)
                        HIDEEZCLOUD=$param
                        shift ;;
                --restart_hes)
                        RESTART_HES=$param
                        shift ;;
                --app_token)
                        APP_TOKEN=$param
                        shift ;;
                --user_name)
                        USER_NAME=$param
                        shift ;;
                --user_email)
                        USER_EMAIL=$param
                        shift ;;
                --user_password)
                        USER_PASSWORD=$param
                        shift ;;
                --) shift
                        break ;;
                        *) echo "ERROR! $1 is not an option"
                        echo "$USAGE"
                        exit 1
                esac
                shift
done


if [ "$PROVIDER" != "MySql" ] && [ "$PROVIDER" != "MsSql" ] ; then
        echo echo "ERROR! $PROVIDER is not a valid database!" | tee -a $LOG_FILE
        exit 1
fi


###SETTING BLOCK
#######################################

# If you want the script to ask no questions, uncomment and fill in these variables
# (USER_PASSWORD must comply with mysql (or mssql) policy!)
#PROVIDER=""
#DOMAIN_NAME=""
#USER_PASSWORD=""
#SMTP_HOST="smtp.example.com"
#SMTP_PORT="123"
#SMTP_USER_NAME="user@example.com"
#SMTP_PASSWORD="password"
#MYSQL_ROOT_PASSWORD=""
#MSSQL_SA_PASSWORD=""
#DATABASE_USER="hesuser"
#DATABASE_NAME="hesdb"
#######################################


#############################################################
# DETECT OS
# "detectOS.sh"  - this script MUST be in the same directory as the installHES.sh file
DIRNAME=$(dirname $0)
if [ ! -f $DIRNAME/detectOS.sh ] ; then
echo "there is no detectOS.sh file in the script directory" | tee -a $LOG_FILE
exit 1
fi
. $DIRNAME/detectOS.sh
echo Detect OS:
echo DIST = $DIST
echo REV = $REV
echo SUB_REV = $SUB_REV

##############################################################

if [ "$PROVIDER" = "MySql" ] ; then
        if [ "$USE_MYSQL_ROOT_PASSWORD" = "1" ] ; then
                if [ -z "$MYSQL_ROOT_PASSWORD" ] 
                then
                        read -s -p "Enter MySQL root password (You installed it earlier): " MYSQL_ROOT_PASSWORD
                        printf "\n"
                fi
        fi
#echo MYSQL_ROOT_PASSWORD = $MYSQL_ROOT_PASSWORD
fi

if [ "$PROVIDER" = "MsSql" ] ; then
if [ -z "$MSSQL_SA_PASSWORD" ] 
then
read -s -p "Enter MS SQL SA password (You installed it earlier): " MSSQL_SA_PASSWORD
printf "\n"
fi
#echo MSSQL_SA_PASSWORD = $MSSQL_SA_PASSWORD
fi

#domain name
if [ -z "$DOMAIN_NAME" ] 
then
read -p "Enter domain name (or leave it blank for use hideez.example.com): " item
DOMAIN_NAME="${item:-hideez.example.com}"
fi

echo DOMAIN_NAME = $DOMAIN_NAME

#DB USER
if [ -z "$DATABASE_USER" ]
then
        read -p "Enter database user (or leave it blank for use hesuser): " item
        DATABASE_USER="${item:-hesuser}"
fi
echo DATABASE_USER = $DATABASE_USER


if [ "$USE_MYSQL_USER_PASSWORD" = "1" ]; then
if [ -z "$USER_PASSWORD" ] 
then
read -s -p "Enter strong password for new database user : " USER_PASSWORD
printf "\n"
fi
fi
#echo USER_PASSWORD = $USER_PASSWORD


#DATABASE_NAME
if [ -z "$DATABASE_NAME" ]
then
read -p "Enter database name (or leave it blank for use hesdb): " item
DATABASE_NAME="${item:-hesdb}"
fi
echo DATABASE_NAME = $DATABASE_NAME

########################### end settings zone

# stopping HES servise (if exist)
if systemctl list-unit-files | grep  $HESSERVICE; then
        systemctl stop $HESSERVICE
fi


#create backup 
if [ -d $HES_DIR ]; then
BACKUP_HES_DIR=$HES_DIR-$(date +%Y-%m-%d-%H-%M-%S)
mv $HES_DIR $BACKUP_HES_DIR
fi


if [ "$PROVIDER" = "MySql" ] ; then
        #Creating MySQL User
        if [ "$USE_MYSQL_ROOT_PASSWORD" = "1" ] ; then
                if [ "$USE_MYSQL_USER_PASSWORD" = "1" ] ; then
                        mysql -u root -p"$MYSQL_ROOT_PASSWORD" -e "CREATE USER IF NOT EXISTS '$DATABASE_USER'@'%' IDENTIFIED BY '$USER_PASSWORD';"
                else
                        mysql -u root -p"$MYSQL_ROOT_PASSWORD" -e "CREATE USER IF NOT EXISTS '$DATABASE_USER'@'%' IDENTIFIED BY '';"
                fi
        else
                if [ "$USE_MYSQL_USER_PASSWORD" = "1" ]
                then
                        mysql -u root -e "CREATE USER IF NOT EXISTS '$DATABASE_USER'@'%' IDENTIFIED BY '$USER_PASSWORD';"
                else
                        mysql -u root -e "CREATE USER IF NOT EXISTS '$DATABASE_USER'@'%' IDENTIFIED BY '';"
                fi
        fi 

        if [ $? -eq 0 ]; then
                echo "sql user successfully created (or updated)" | tee -a $LOG_FILE
        else
                # ups.... 
                echo "error creating mysql user" | tee -a $LOG_FILE
                exit 1
        fi

        #Drop MySQL Database (if exists) and 
        #creating MySQL Database for the Hideez Enterprise Server

        DATABASE_NAME_FOR_MYSQL=$DATABASE_NAME 
        #if name of database base contains a character "-"
        # then the name of the base must be enclosed in reverse apostrophe
        if [[ "$DATABASE_NAME" == *"-"* ]]; then
                DATABASE_NAME_FOR_MYSQL="\`$DATABASE_NAME\`"
        fi
        mysql -u root -p"$MYSQL_ROOT_PASSWORD" --execute="DROP DATABASE IF EXISTS $DATABASE_NAME_FOR_MYSQL; CREATE DATABASE $DATABASE_NAME_FOR_MYSQL; GRANT ALL ON $DATABASE_NAME_FOR_MYSQL.* TO '$DATABASE_USER'@'%'; FLUSH PRIVILEGES;"

        if [ $? -eq 0 ]; then
                echo "database successfully created" | tee -a $LOG_FILE
        else
        # ups.... 
                echo "error creating mysql database db" | tee -a $LOG_FILE
                exit 1
        fi
fi #mysql


if [ "$PROVIDER" = "MsSql" ] ; then
        /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "$MSSQL_SA_PASSWORD" -Q "CREATE LOGIN [$DATABASE_USER] WITH PASSWORD = '$USER_PASSWORD', CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF  "
        /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "$MSSQL_SA_PASSWORD" -Q "CREATE DATABASE $DATABASE_NAME"
        /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "$MSSQL_SA_PASSWORD" -Q "USE $DATABASE_NAME; CREATE USER [$DATABASE_USER] from login [$DATABASE_USER]; GRANT CONTROL ON DATABASE::$DATABASE_NAME TO [$DATABASE_USER] "
        if [ $? -eq 0 ]; then
                echo "databse and ms sql user successfully created" | tee -a $LOG_FILE
        else
        # ups.... 
                echo "error creating ms sql database user or db" | tee -a $LOG_FILE
                exit 1
        fi

fi #MS sql

################################


if [ "$FROM_TEMPLATE" = "0" ] ; then

        TMPDIR=$(mktemp -d)
        curl -H "Cache-Control: no-cache" -u "$URL_LOGIN":"$URL_PASSWORD" -o "$TMPDIR/hes.tar.gz" $HES_URL
        #echo "curl -H "Cache-Control: no-cache" -u "$URL_LOGIN":"$URL_PASSWORD" -o "$TMPDIR/hes.tar.gz" $HES_URL"

        if [ $? -eq 0 ]; then
                echo "file  hes.tar.gz to $TMPDIR  file uploaded successfull from $HES_URL" | tee -a $LOG_FILE
        else
                echo "Download error file from $HES_URL  to $TMPDIR" | tee -a $LOG_FILE
                exit 1
        fi
        #echo "run   tar -xf "$TMPDIR/hes.tar.gz" -C "$TMPDIR" "
        tar -zxvf "$TMPDIR/hes.tar.gz" -C "$TMPDIR"

        if [ $? -eq 0 ]; then
                echo "the archive is unpacked successfull" | tee -a $LOG_FILE
        else
                echo "error unpacking the $TMPDIR/hes.tar.gz file " | tee -a $LOG_FILE
                exit 1
        fi

        mv "$TMPDIR/HES" "$HES_DIR"

        if [ $? -eq 0 ]; then
                echo "files from $TMPDIR/HES successfully moved to $HES_DIR" | tee -a $LOG_FILE
        else
                echo "error moving files from $TMPDIR/HES to $HES_DIR !!!" | tee -a $LOG_FILE
                exit 1
        fi

        rm -rf "$TMPDIR"
        if [ $? -eq 0 ]; then
                echo "$TMPDIR removed successfully" | tee -a $LOG_FILE
        else
                echo "error removed $TMPDIR !!!" | tee -a $LOG_FILE
                exit 1
        fi
else
        cp -r "$TEMPLATE_DIR" "$HES_DIR"

        if [ $? -eq 0 ]; then
                echo "files from $TEMPLATE_DIR to $HES_DIR copied successfully" | tee -a $LOG_FILE
        else
                echo "error copyng files from $TEMPLATE_DIR to $HES_DIR !!!" | tee -a $LOG_FILE
                exit 1
        fi

fi #from template


################################


if [ "$CONFIG_NGINX" = "1" ] ;then
        ################################
        #Configuring the Nginx Reverse Proxy

        CERT_DIR="/etc/nginx/certs"

        #create certs for nginx
        if [ ! -d $CERT_DIR ]; then
        mkdir $CERT_DIR
        fi


        TMPDIR=$(mktemp -d)


        # https://devopscube.com/create-self-signed-certificates-openssl/
        #Create Certificate Authority
        openssl req -x509 \
                -sha256 -days 3560 \
                -nodes \
                -newkey rsa:2048 \
                -subj "/CN=Root CA" \
                -keyout $CERT_DIR/CA.key -out $CERT_DIR/CA.crt 

        # Create the HES server Private Key
        openssl genrsa -out $CERT_DIR/hes.key 2048

        # Create Certificate Signing Request Configuration

        CSR_CONF_FILE="$TMPDIR/csr.conf"
                
        cat > $CSR_CONF_FILE <<EOF
        [ req ]
        default_bits = 2048
        prompt = no
        default_md = sha256
        req_extensions = req_ext
        distinguished_name = dn

        [ dn ]
        CN = $DOMAIN_NAME

        [ req_ext ]
        subjectAltName = @alt_names

        [ alt_names ]
        DNS.1 = $DOMAIN_NAME
EOF

        #  Generate Certificate Signing Request (CSR) Using Server Private Key
        openssl req -new -key $CERT_DIR/hes.key -out $CERT_DIR/hes.csr -config $CSR_CONF_FILE

        # Create a external file

        CERT_CONF_FILE="$TMPDIR/cert.conf"

        cat > $CERT_CONF_FILE <<EOF

        authorityKeyIdentifier=keyid,issuer
        basicConstraints=CA:FALSE
        keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
        subjectAltName = @alt_names

        [alt_names]
        DNS.1 = $DOMAIN_NAME
EOF

        # Generate SSL certificate With self signed CA

        openssl x509 -req \
        -in $CERT_DIR/hes.csr \
        -CA $CERT_DIR/CA.crt -CAkey $CERT_DIR/CA.key \
        -CAcreateserial -out $CERT_DIR/hes.crt \
        -days 3650 \
        -sha256 -extfile $CERT_CONF_FILE


        rm -rf "$TMPDIR"

        #=================================================


        #Configuration for the Nginx Reverse Proxy

        OLD_NGINX="/etc/nginx/nginx.conf.without_HES"
        cp /etc/nginx/nginx.conf $OLD_NGINX  

        if [[ $DIST == "CentOS Linux" ]]  && [[ $SUB_REV  == "7" ]]; then
                cp $HES_DIR/Deploy/CentOS7/nginx.conf   /etc/nginx/nginx.conf
        elif [[ $DIST == "CentOS Stream" ]]  && [[ $SUB_REV  == "8" ]]; then
                cp $HES_DIR/Deploy/CentOS8/nginx.conf /etc/nginx/nginx.conf
        elif [[ $DIST == "CentOS Stream" ]]  && [[ $SUB_REV  == "9" ]]; then
                cp $HES_DIR/Deploy/CentOS9/nginx.conf /etc/nginx/nginx.conf
        elif [[ $DIST == "Ubuntu" ]]  && [[ $REV  == "18.04" ]]; then
                cp $HES_DIR/Deploy/Ubuntu18/nginx.conf   /etc/nginx/nginx.conf
        elif [[ $DIST == "Ubuntu" ]]  && [[ $REV  == "20.04" ]]; then
                cp $HES_DIR/Deploy/Ubuntu20/nginx.conf  /etc/nginx/nginx.conf
        elif [[ $DIST == "Ubuntu" ]]  && [[ $REV  == "22.04" ]]; then
                cp $HES_DIR/Deploy/Ubuntu22/nginx.conf  /etc/nginx/nginx.conf
        elif [[ $DIST == "Ubuntu" ]]  && [[ $REV  == "24.04" ]]; then
                cp $HES_DIR/Deploy/Ubuntu22/nginx.conf  /etc/nginx/nginx.conf
        elif [[ $DIST == "Amazon Linux" ]] && [[ $REV  == "2023" ]]; then
                cp $HES_DIR/Deploy/CentOS9/nginx.conf /etc/nginx/nginx.conf
        elif [[ $DIST == "Amazon Linux" ]] && [[ $REV  == "2" ]]; then
                cp $HES_DIR/Deploy/CentOS7/nginx.conf /etc/nginx/nginx.conf
        fi

        if [ -f /etc/nginx/sites-enabled/default ]; then
                rm /etc/nginx/sites-enabled/default
        fi

else
        bash $DIRNAME/create_nginx_conf.sh --domain_name $DOMAIN_NAME --hes_port $HES_PORT
fi  # config nginx

#Restarting the Nginx Reverse Proxy and check its status
systemctl reload nginx
#sudo systemctl status nginx

################################


# #save setting to file
# FILE_SETTING=$HOME/$DOMAIN_NAME-setting.txt
# ##   

# #echo DOMAIN_NAME = $DOMAIN_NAME
# #echo FILE_SETTING = $FILE_SETTING
# ##   
# BACKUP_SETTING=$HOME/$DOMAIN_NAME-setting$(date +%Y-%m-%d-%H-%M-%S).txt
# if [ -f $FILE_SETTING ]; then
# mv $FILE_SETTING $BACKUP_SETTING
# fi

# cat > $FILE_SETTING << EOF
# DOMAIN_NAME = $DOMAIN_NAME
# DATABASE_NAME = $DATABASE_NAME
# DATABASE_USER = $DATABASE_USER
# USER_PASSWORD = $USER_PASSWORD
# SMTP_HOST = $SMTP_HOST
# SMTP_PORT = $SMTP_PORT
# SMTP_USER_NAME = $SMTP_USER_NAME
# SMTP_PASSWORD = $SMTP_PASSWORD
# EOF

# cat $FILE_SETTING

# echo "  for testing status HES server:" | tee -a $LOG_FILE
# echo "sudo systemctl status $HESSERVICE.service" | tee -a $LOG_FILE
# echo "In your home directory, has been created file $DOMAIN_NAME-setting.txt with your settings." | tee -a $LOG_FILE
# echo "For your safety, after making sure everything works, it is advised to save your settings somewhere and delete this file" | tee -a $LOG_FILE


SERVICE_FILE="/lib/systemd/system/$HESSERVICE.service"

#  Daemonizing Hideez Enterprise Server
cp $HES_DIR/Deploy/HES.service  "$SERVICE_FILE"

#change path in service
sed -i "s#WorkingDirectory=/opt/HES#WorkingDirectory=$HES_DIR#" "$SERVICE_FILE"
sed -i "s#ExecStart=/opt/HES/HES.Web#ExecStart=$HES_DIR/HES.Web#" "$SERVICE_FILE"
systemctl daemon-reload


#change run HES service with parameters
HES_PARAMETERS=" --app_token $APP_TOKEN --user_name $USER_NAME --user_email $USER_EMAIL --user_password $USER_PASSWORD"
sed -i "s#HES.Web#HES.Web $HES_PARAMETERS#" "$SERVICE_FILE"


# Run wizard
if [ "$RUN_WIZARD" = "1" ] ; then
        cd $HES_DIR
        ./HES.Wizard
else
        bash $DIRNAME/create_appsettings.sh --database_name $DATABASE_NAME --database_user $DATABASE_USER --domain_name $DOMAIN_NAME --json_file $HES_DIR/appsettings.Production.json --hes_port $HES_PORT --smtp_host $SMTP_HOST --smtp_port $SMTP_PORT --enablessl $ENABLESSL --smtp_user_name $SMTP_USER_NAME --smtp_password $SMTP_PASSWORD --hideezcloud $HIDEEZCLOUD
fi


systemctl start $HESSERVICE.service

if [ "$ADD_RECORDS_TO_BASE" = "1" ] ; then
        echo "waiting while database creating..."
        sleep 10s
        bash $DIRNAME/add_records.sh --provider $PROVIDER --database_name $DATABASE_NAME --use_mysql_root_password $USE_MYSQL_ROOT_PASSWORD --mysql_root_password $MYSQL_ROOT_PASSWORD --smtp_host $SMTP_HOST --smtp_port $SMTP_PORT --enablessl $ENABLESSL --smtp_user_name $SMTP_USER_NAME --smtp_password $SMTP_PASSWORD
fi

# echo "RESTART_HES = $RESTART_HES"
if [ "$RESTART_HES" = "1" ] ; then 
        echo "waiting 60 s while HES creating..."
        sleep 60s
        systemctl restart $HESSERVICE.service
fi


systemctl enable $HESSERVICE.service

echo "Done!" 

