#!/bin/bash

SCRIPT_VER="1.5"

APP="SyncThing"
APP_CATEGORY="Sync Solutions"
APP_SCOPE="user"
STORED_PASSWORD_SERVICE="syncthing"
SUPPORTED_ON="Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="yes"
APP_ENABLED="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

while : ; do

    main_rc=1

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

    systemctl is-enabled "syncthing@root" > /dev/null 2>&1 \
        && SVC_DISABLE "syncthing@root"
    systemctl is-active "syncthing@root" > /dev/null 2>&1 \
        && SVC_STOP    "syncthing@root"
    [ -d "/root/.config/syncthing" ] \
        && RM_DIRS "/root/.config/syncthing"

    SVC_DISABLE "syncthing@${USERNAME}"
    SVC_STOP    "syncthing@${USERNAME}"
    RM_DIRS "${USERHOME}/.config/syncthing"

    # Configure `apache2` service
    if [ -e "/etc/apache2/userconf-enabled/syncthing-${USERNAME}.conf" ] ; then
        RM_FILES "/etc/apache2/userconf-enabled/syncthing-${USERNAME}.conf"
        SVC_RESTART "apache2"
    fi


    # It was last user Transmission? - Will delete `transmission-daemon` from machine....
    ret="$( find /home -type d -a -iwholename '*/.config/syncthing' )"
    if [ -z "${ret[@]}" ] ; then
        DPKG_REMOVE "syncthing"
        APT_AUTOREMOVE
        RM_FILES    "/etc/systemd/system/syncthing@.service" \
                    "/etc/systemd/system/syncthing.slice"
         if [ -d "/etc/systemd/system/syncthing@.service.d" ] ; then
             RM_DIRS "/etc/systemd/system/syncthing@.service.d"
         fi
        SYSTEMD_RELOAD
        RM_FILES    "/etc/apt/sources.list.d/syncthing.list" \
            && APT_UPDATE
    fi


    main_rc=0
    break

done


SCRIPTEXIT
