#!/bin/bash

SCRIPT_VER="1.4"

APP="SoftEtherVPN"
APP_CATEGORY="System Services"
APP_ENABLED="yes"
SUPPORTED_ON="Debian10,Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
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


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 uninstall this application for the user account '${USERNAME}'"
        break
    fi

    # -- monit configs
    if [ -e "/etc/monit/conf.d/vpnserver" ] ; then
        RM_FILES "/etc/monit/conf.d/vpnserver"
        MONIT_RELOAD
    fi
    SVC_STOP    "vpnserver"
    SVC_DISABLE "vpnserver"

    # -- Uninstall 'softethervpn'
    ${PKG_REMOVE} "softethervpn"

    # -- Remove logs
    RM_DIRS "/var/log/vpnserver"

    # -- Re-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"
          # 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"
          # 3. Save rules
          RUN_LOG "service iptables save"
          ;;
      "Debian"|"Ubuntu")
          ;;
    esac

    # -- Remove misc stuff
    [ -e "/etc/systemd/system/vpnserver.service" ] && RM_FILES "/etc/systemd/system/vpnserver.service"
    [ -e "/etc/cron.d/vpnserver-clean-logs" ] && RM_FILES "/etc/cron.d/vpnserver-clean-logs"
    [ -e "/etc/init.d/vpnserver" ] && RM_FILES "/etc/init.d/vpnserver"
    for d in "vpnbridge" "vpnclient" "vpncmd" "vpnserver" ; do
        [ -d "/usr/${d}" ] && RM_DIRS "/usr/${d}"
    done


    main_rc=0
    break

done

SCRIPTEXIT
