#!/bin/bash

SCRIPT_VER="1.4"

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

IPSEC_PSK="12345"

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


while : ; do

    main_rc=1

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

    if [ "${USERUID}" != "${FIRST_UID}" ] ; then
        ERROR "Cannot install this application for the user account '${USERNAME}'"
        break
    fi

    case "${LSB_VENDOR}" in
      "CentOS")
          ${PKG_INSTALL} \
                "git-core" \
                "readline-devel" \
                "ncurses-devel" \
                "openssl-devel" \
                "rpm-build" \
                "rpmdevtools" \
             || break
          YUM_GROUPINSTALL "Development Tools" || break
          GIT_CLONE "http://checkinstall.izto.org/checkinstall.git" \
                    "${TMP_DIR}/checkinstall" \
                || break
          oWD=$( pwd )
          cd "${TMP_DIR}/checkinstall"
          RUN_LOG "make" || break
          RUN_LOG "make install" || break
          cd "${oWD}"
          INSTALL_CMD="rpmdev-setuptree && checkinstall -y --type=rpm --pkgname=softethervpn --install=yes"
          ;;
      "Debian"|"Ubuntu")
          ${PKG_INSTALL} \
                "git-core" \
                "build-essential" \
                "cmake" \
                "libreadline-dev" \
                "libncurses-dev" \
                "libssl-dev" \
                "zlib1g-dev" \
                "checkinstall" \
             || break
          INSTALL_CMD="checkinstall -y --type=debian --install=yes"
          ;;
    esac
    GIT_CLONE "https://github.com/SoftEtherVPN/SoftEtherVPN_Stable.git" \
              "${TMP_DIR}/SoftEtherVPN" \
       || break

    L_LOG
    INFO "Build & Install ${APP}"
    L_LOG
    # Get SoftEtherVPN version info
    _VERSION="$( awk '/VERSION/{print $2}' "${TMP_DIR}/SoftEtherVPN/src/CurrentBuild.txt" \
                        | sed -e 's/[^[:alnum:]]//g' )"
    _BUILD_NUMBER="$( awk '/BUILD_NUMBER/{print $2}' "${TMP_DIR}/SoftEtherVPN/src/CurrentBuild.txt" \
                        | sed -e 's/[^[:alnum:]]//g' )"
    INSTALL_CMD="${INSTALL_CMD} --pkgversion=${_VERSION}.${_BUILD_NUMBER}"
    [ "${DEBUG}" = "yes" ] && INSTALL_CMD="${INSTALL_CMD} -d2"
    #
    #
    oWD=$( pwd )
    cd "${TMP_DIR}/SoftEtherVPN"
    RUN_LOG "./configure" || break
    RUN_LOG "make" || break
    RUN_LOG "${INSTALL_CMD}" || break
    cd "${oWD}"

    # Configure logging
    MKDIR "/var/log/vpnserver"
    LN "/usr/vpnserver/packet_log" "/var/log/vpnserver/packet_log"
    LN "/usr/vpnserver/security_log" "/var/log/vpnserver/security_log"
    LN "/usr/vpnserver/server_log" "/var/log/vpnserver/server_log"

    # Configure 'iptables'
    case "${LSB_VENDOR}" in
      "CentOS")
          # 1. ISAKMP (handling of security associations)
          RUN_LOG "iptables -D INPUT -p udp -m udp --dport 500 -m conntrack --ctstate NEW -j ACCEPT"
          RUN_LOG "iptables -A INPUT -p udp -m udp --dport 500 -m conntrack --ctstate NEW -j ACCEPT"
          # 2. NAT-T (handling of IPsec between natted devices)
          RUN_LOG "iptables -D INPUT -p udp -m udp --dport 4500 -m conntrack --ctstate NEW -j ACCEPT"
          RUN_LOG "iptables -A INPUT -p udp -m udp --dport 4500 -m conntrack --ctstate NEW -j ACCEPT"
          # 3. Fallback rule(s)
          RUN_LOG "iptables -D INPUT -j REJECT --reject-with icmp-host-prohibited" \
              && RUN_LOG "iptables -A INPUT -j REJECT --reject-with icmp-host-prohibited"
          RUN_LOG "iptables -D INPUT -j LOGGING" \
              && RUN_LOG "iptables -A INPUT -j LOGGING"
          # 4. Save rules
          RUN_LOG "service iptables save"
          ;;
      "Debian"|"Ubuntu")
          ;;
    esac

    VPNSERVER_PIDFILE="$( grep -e '^pidfile=' "${TMP_DIR}/SoftEtherVPN/centos/SOURCES/init.d/vpnserver" \
                                      | sed -e 's/^pidfile=\(.*\)$/\1/' )"
    INFO "pid: [${VPNSERVER_PIDFILE}]"

    # Configure service
    if [ "${SVC_SYSTEM}" = "systemd" ] ; then
        CP_FILE "${TMP_DIR}/SoftEtherVPN/systemd/softether-vpnserver.service" \
                "/etc/systemd/system/vpnserver.service"
        if [ $? -eq 0 ] ; then
            RUN_LOG "sed -i -e 's#/opt/vpnserver#/usr/vpnserver#g' '/etc/systemd/system/vpnserver.service'"
        fi
    fi
    SVC_ENABLE "vpnserver"
    SVC_START  "vpnserver"

    # Configure SoftEtherVPN
    # -- Change Server admin oassword
    # vpncmd localhost:5555 /SERVER [/PASSWORD:CurrentServerPassword] /CMD ServerPasswordSet ChangeMe
    # -- Check server functions
    # vpncmd localhost:5555 /SERVER /CMD check
    # -- Get various server props
    # vpncmd localhost:5555 /SERVER /CMD ServerStatusGet
    # vpncmd localhost:5555 /SERVER /CMD ServerInfoGet
    # -- List listeners
    # vpncmd localhost:5555 /SERVER /PASSWORD:ChangeMe /CMD ListenerList
    # -- Delete HTTPS listener
    # vpncmd localhost:5555 /SERVER /PASSWORD:ChangeMe /CMD ListenerDelete 443
    # -- Disable keep-alive function - no connections to the foreign keep-alive collector
    # vpncmd localhost:5555 /SERVER /Password:ChangeMe1 /CMD KeepDisable
    # -- Get server capabilities
    # vpncmd localhost:5555 /SERVER /Password:ChangeMe1 /CMD Caps
    # -- Get the content of Server config file
    # vpncmd localhost:5555 /SERVER /Password:ChangeMe1 /CMD ConfigGet
    # -- Enable IPsec
    # vpncmd localhost:5555 /SERVER /Password:ChangeMe1 /CMD IPsecEnable [/L2TP:yes|no] [/L2TPRAW:yes|no] [/ETHERIP:yes|no] [/PSK:pre-shared-key] [/DEFAULTHUB:default_hub]
    # -- Enable/Disable OpenVPN server
    # vpncmd localhost:5555 /SERVER /Password:ChangeMe1 /CMD OpenVpnEnable [yes|no] [/PORTS:udp_port_list]

    i=1
    while [ ${i} -le 10 ] ; do
        RUN_LOG "service vpnserver status > /dev/null 2>&1" && break
        i=$((i+1))
        INFO "[${i}]: Waiting for 'vpnserver' to become active..."
        RUN_LOG "sleep 5"
    done

    RUN_LOG "sleep 5"
    if RUN_LOG "service vpnserver status > /dev/null 2>&1" ; then
        # -- Change Server admin password
        RUN_LOG "vpncmd localhost:5555 /SERVER \
                        /CMD ServerPasswordSet ${USERPASSWORD}"
        # -- Change DEFAULT Hub password
        RUN_LOG "vpncmd localhost:5555 /SERVER /HUB:DEFAULT \
                        /CMD SetHubPassword ${USERPASSWORD}"
        # -- Delete HTTPS listener
        RUN_LOG "vpncmd localhost:5555 /SERVER /PASSWORD:${USERPASSWORD} \
                        /CMD ListenerDelete 443"
        # -- Delete TELNET over SSL listener
        RUN_LOG "vpncmd localhost:5555 /SERVER /PASSWORD:${USERPASSWORD} \
                        /CMD ListenerDelete 992"
        # -- Disable keep-alive function - no connections to the foreign keep-alive collector
        RUN_LOG "vpncmd localhost:5555 /SERVER /PASSWORD:${USERPASSWORD} \
                        /CMD KeepDisable"
        # -- Disable OpenVPN server
        RUN_LOG "vpncmd localhost:5555 /SERVER /PASSWORD:${USERPASSWORD} \
                        /CMD OpenVpnEnable no /PORTS:1194"
        # -- Delete OpenVPN listener
        RUN_LOG "vpncmd localhost:5555 /SERVER /PASSWORD:${USERPASSWORD} \
                        /CMD ListenerDelete 1194"
        # -- Enable IPsec
        RUN_LOG "vpncmd localhost:5555 /SERVER /PASSWORD:${USERPASSWORD} \
                        /CMD IPsecEnable /L2TP:yes \
                        /L2TPRAW:no \
                        /ETHERIP:no \
                        /PSK:${IPSEC_PSK} \
                        /DEFAULTHUB:DEFAULT"
        # -- Enable SecureNAT and Virtual DHCP server
        RUN_LOG "vpncmd localhost:5555 /SERVER /PASSWORD:${USERPASSWORD} /HUB:DEFAULT \
                        /CMD SecureNatEnable"
        RUN_LOG "vpncmd localhost:5555 /SERVER /PASSWORD:${USERPASSWORD} /HUB:DEFAULT \
                        /CMD SecureNatHostSet /MAC:none /IP:10.254.254.1 /MASK:255.255.255.0"
        RUN_LOG "vpncmd localhost:5555 /SERVER /PASSWORD:${USERPASSWORD} /HUB:DEFAULT \
                        /CMD DhcpSet \
                                /EXPIRE:3600 \
                                /DOMAIN:rapidseedbox.com \
                                /START:10.254.254.2 \
                                /END:10.254.254.200 \
                                /MASK:255.255.255.0 \
                                /GW:10.254.254.1 \
                                /DNS:8.8.8.8 \
                                /DNS2:8.8.4.4 \
                                /LOG:yes"
        # -- Create 'user' account
        RUN_LOG "vpncmd localhost:5555 /SERVER /HUB:DEFAULT /PASSWORD:${USERPASSWORD} \
                        /CMD UserCreate ${USERNAME} \
                        /GROUP:none \
                        /REALNAME:\"RSB User\" \
                        /NOTE:none"
        RUN_LOG "vpncmd localhost:5555 /SERVER /HUB:DEFAULT /PASSWORD:${USERPASSWORD} \
                        /CMD UserPasswordSet ${USERNAME} \
                        /PASSWORD:${USERPASSWORD}"
        # -- Set DDNS hostname: 'box-ip-add-re-ss.softether.net'
        RUN_LOG "vpncmd localhost:5555 /SERVER /Password:${USERPASSWORD} \
                        /CMD DynamicDnsSetHostname box-$( echo "${IP}" | tr '.' '-' )"
    fi

    # -- monit configs
    if [ -e "/etc/monit/conf.d" -a -n "${VPNSERVER_PIDFILE}" ] ; then
        cat <<-EOF > "/etc/monit/conf.d/vpnserver" 2>> "${LOGFILE}"
	check process vpnserver with pidfile ${VPNSERVER_PIDFILE}
	  start program = "/usr/sbin/service vpnserver restart"
	  stop program = "/usr/sbin/service vpnserver stop"
	  if failed host localhost port 5555 type tcp then restart
	  if failed host localhost port 500 type udp then restart
	  if failed host localhost port 4500 type udp then restart
	EOF
        MONIT_RELOAD
    fi

    cat <<-EOF > "/etc/cron.d/vpnserver-clean-logs" 2>> "${LOGFILE}"
	SHELL=/bin/bash
	PATH=/sbin:/bin:/usr/sbin:/usr/bin
	MAILTO=root
	HOME=/
	5 * * * * root find /usr/vpnserver -type f -wholename "/usr/vpnserver/*_log/*.log" -mtime 31
	EOF


    main_rc=0
    break

done



SCRIPTEXIT
