#!/bin/bash

SCRIPT_VER="1.4"

APP="WebSSH"
APP_CATEGORY="System Services"
APP_SCOPE="system"
APP_ENABLED="yes"
SUPPORTED_ON="Debian9,Debian10,Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="yes"
LIBRARY="functions4.sh"

if [ "${SUPPORT-}" = '' ]; then
    SUPPORT="https://installers.rapidseedbox.com/scripts/whmcs_client_installers/support"
fi

LOGFILE="/var/log/whmcs_client_installers/${0}.log"
[ ! -d "/var/log/whmcs_client_installers" ] && mkdir -p "/var/log/whmcs_client_installers"

wget -4 -nc -q --no-check-certificate --timeout=20 --tries=5 ${SUPPORT}/${LIBRARY} >> "${LOGFILE}" 2>&1
if [ ! -f "./${LIBRARY}" ] ; then
    echo "55"
    echo "Error downloading \"${SUPPORT}/${LIBRARY}\"" >> "${LOGFILE}"
    exit 55
fi

# shellcheck source=support/functions4.sh
. "./${LIBRARY}"
SCRIPTENTRY

VALIDATE_USER

APP_DIRECTORY="/opt/WebSSH2"

while : ; do

    main_rc=1

    CHECK_APP ; _rc=$?
    if [ ${_rc} -ne 0 ] ; then
        main_rc=${_rc}
        break
    fi

##    if ! which npm > /dev/null 2>&1 ; then
#        APT_INSTALL "curl" || break
##        RUN_LOG "curl -sL https://deb.nodesource.com/setup_12.x | bash -" || break
#        RUN_LOG "curl -fsSL https://deb.nodesource.com/setup_15.x | bash -" || break
#        APT_UPDATE || break
#        APT_INSTALL "nodejs" || break
##    fi

#    APT_INSTALL "wget" || break
#    RUN_LOG "wget -qO- https://deb.nodesource.com/setup_lts.x | bash -" || break
#    APT_INSTALL "nodejs" || break

    NODEJS_INSTALL || break

    GIT_CLONE "https://github.com/billchurch/WebSSH2/" "${APP_DIRECTORY}" || break

    oWD="$( pwd )"
    cd "${APP_DIRECTORY}/app"
    RUN_LOG "npm install --production" || break
#    RUN_LOG "npm audit fix" || break
    cd "${oWD}"

    cat <<-EOF > "${APP_DIRECTORY}/app/config.json"
	{
	  "listen": {
	    "ip": "127.0.0.1",
	    "port": 12222
	  },
	  "http": {
	    "origins": ["*:*"]
	  },
	  "user": {
	    "name": null,
	    "password": null,
	    "privatekey": null
	  },
	  "ssh": {
	    "host": "127.0.0.1",
	    "port": 2222,
	    "term": "xterm-color",
	    "readyTimeout": 20000,
	    "keepaliveInterval": 120000,
	    "keepaliveCountMax": 10,
	    "allowedSubnets": []
	  },
	  "terminal": {
	    "cursorBlink": true,
	    "scrollback": 10000,
	    "tabStopWidth": 8,
	    "bellStyle": "sound"
	  },
	  "header": {
	    "text": null,
	    "background": "green"
	  },
	  "session": {
	    "name": "WebSSH2",
	    "secret": "$( uuidgen )"
	  },
	  "options": {
	    "challengeButton": true,
	    "allowreauth": true
	  },
	  "algorithms": {
	    "kex": [
	      "ecdh-sha2-nistp256",
	      "ecdh-sha2-nistp384",
	      "ecdh-sha2-nistp521",
	      "diffie-hellman-group-exchange-sha256",
	      "diffie-hellman-group14-sha1"
	    ],
	    "cipher": [
	      "aes128-ctr",
	      "aes192-ctr",
	      "aes256-ctr",
	      "aes128-gcm",
	      "aes128-gcm@openssh.com",
	      "aes256-gcm",
	      "aes256-gcm@openssh.com",
	      "aes256-cbc"
	    ],
	    "hmac": [
	      "hmac-sha2-256",
	      "hmac-sha2-512",
	      "hmac-sha1"
	    ],
	    "compress": [
	      "none",
	      "zlib@openssh.com",
	      "zlib"
	    ]
	  },
	  "serverlog": {
	    "client": false,
	    "server": false
	  },
	  "accesslog": false,
	  "verify": false,
	  "safeShutdownDuration": 300
	}
	EOF

    _svc_file="/etc/systemd/system/webssh.service"
    cat <<-EOF > "${_svc_file}"
	[Service]
	WorkingDirectory=${APP_DIRECTORY}/app
	ExecStart=/usr/bin/npm start
	TimeoutStopSec=30
	Restart=always
	StandardOutput=null
	#StandardOutput=syslog
	#StandardError=syslog
	#SyslogIdentifier=notell
	User=root
	Group=root
	Environment=NODE_ENV=production

	[Install]
	WantedBy=multi-user.target
	EOF
    SYSTEMD_RELOAD
    SVC_ENABLE "webssh" || break
    SVC_START  "webssh" || break

    _apache_conf="/etc/apache2/userconf-enabled/webssh.conf"
    if [ ! -d "/etc/apache2/userconf-enabled/" ] ; then
        MKDIR "/etc/apache2/userconf-enabled" || break
    fi
    cat <<-EOF > "${_apache_conf}"
	RewriteEngine on 
	RewriteRule ^/ssh$ /ssh/host/127.0.0.1/ [R=permanent]
	RewriteRule ^/ssh/$ /ssh/host/127.0.0.1/ [R=permanent]
	<Location /ssh/> 
	   ProxyPreserveHost Off 
	   ProxyPass http://127.0.0.1:12222/ssh/ 
	   ProxyPassReverse http://127.0.0.1:12222/ssh/ 
	   Order Allow,Deny 
	   Allow from All
	</Location>
	EOF

    RUN_LOG "apachectl -t" || break
    SVC_RESTART "${APACHE_SVC}"


    main_rc=0
    break

done


# Cleanup if error
if [ ${main_rc} -ne 0 -a ${main_rc} -ne 111 -a ${main_rc} -ne 117 ] ; then
    ERROR "'${APP}': Starting cleanup procedure"
    SVC_DISABLE "webssh"
    SVC_STOP  "webssh"
    if [ -e "/etc/apache2/userconf-enabled/webssh.conf" ] ; then
        RM_FILES "/etc/apache2/userconf-enabled/webssh.conf"
        SVC_RESTART "${APACHE_SVC}"
    fi
    RM_DIRS "${APP_DIRECTORY}"
fi

SCRIPTEXIT
