#!/bin/bash

SCRIPT_VER="1.4"

APP="Overseerr"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="system"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="user"
#><#APP_CHECK_VER_CMD="if which snap > /dev/null 2>&1 ; then snap list | awk -v app=overseerr "\$1 == app {print \$2}" | tr -d "v" ; else echo "" ; fi"
SUPPORTED_ON="Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="yes"
DAEMON_PORT=5055
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

# References:
# https://docs.overseerr.dev/getting-started/installation

while : ; do

    main_rc=1

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

#    _virt_type="$( systemd-detect-virt )"
#    case "${_virt_type}" in
#      "lxc")
#          main_rc=113
#          ERROR "'snap' is not available on LXC containers"
#          break
#          ;;
#    esac

    # -- Install required packages
    APT_INSTALL "snap" "snapd"
    RUN_LOG "apt-get install -f 2>&1" || break
    SVC_RESTART "udev"
    RUN_LOG "udevadm control --reload 2>&1"

    # -- Install `overseerr` - with UGLY hack to make it possible to install on LXC (NGv3) VPS
    RUN_LOG "snap install overseerr 2>&1"
    RUN_LOG "snap install overseerr 2>&1" || break

    # -- Configure `systemd` service unit
    [ ! -d "/etc/systemd/system/snap.overseerr.daemon.service.d" ] \
        && MKDIR "/etc/systemd/system/snap.overseerr.daemon.service.d"
    cat <<-EOF > "/etc/systemd/system/snap.overseerr.daemon.service.d/override.conf"
	[Service]
	Environment=HOST=127.0.0.1
	EOF
    SYSTEMD_RELOAD
    systemctl is-active "snap.overseerr.daemon.service.d" > /dev/null 2>&1 \
        && SVC_RESTART "snap.overseerr.daemon.service.d"
     

#    # -- Configure Apache virtual site
#    if which "easy-ssl" > /dev/null 2>&1 ; then
#        _flag=""
#        if grep -q -E '//installers\.seedbox\.vip/' <<< "${SUPPORT}" ; then
#            _flag="-t"
#        fi
#        sleep 10
#        RUN_LOG "easy-ssl -b ${_flag} 2>&1"
#    fi


    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}': Installation failed."
    # Cleanup tasks here
fi

SCRIPTEXIT
