#!/bin/bash

SCRIPT_VER="1.7"

APP="Headphones"
APP_CATEGORY="Multimedia"
APP_SCOPE="user"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="user"
#><#APP_CHECK_VER_CMD="[ -e "/opt/headphones/version.id" ] && cat "/opt/headphones/version.id" || echo """
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04,Ubuntu24.04"
USE_APACHE2="yes"
DAEMON_PORT=8182
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="${USERHOME}/.headphones"
APP_HOME="/opt/headphones"
APP_CONFIG="${APP_DIRECTORY}/config.ini"

while : ; do

    main_rc=1

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

    APT_INSTALL "python3" "unzip" "crudini" || break

    if [ ! -s "${APP_HOME}/version.id" ] ; then
        GITHUB_RELEASE "rembo10/headphones" "latest" "" "zip" || break
        HEADPHONES_VERSION="${GITHUB_RELEASE_TAG#v}"
        if [ -z "${HEADPHONES_VERSION}" ] ; then
            ERROR "Failed to determine latest ${APP} release tag."
            break
        fi

        HEADPHONES_EXTRACT_DIR="${TMP_DIR}/headphones-${HEADPHONES_VERSION}"
        [ -d "${HEADPHONES_EXTRACT_DIR}" ] && RM_DIRS "${HEADPHONES_EXTRACT_DIR}"
        MKDIR "${HEADPHONES_EXTRACT_DIR}" || break

        WGET "${GITHUB_RELEASE_ASSET_URL}" "${GITHUB_RELEASE_ASSET_NAME}" || break
        UNZIP "${TMP_DIR}/${GITHUB_RELEASE_ASSET_NAME}" "${HEADPHONES_EXTRACT_DIR}" || break
        HEADPHONES_SRC_DIR="$( find "${HEADPHONES_EXTRACT_DIR}" -mindepth 1 -maxdepth 1 -type d | head -1 )"
        if [ -z "${HEADPHONES_SRC_DIR}" ] ; then
            ERROR "Failed to extract ${APP} release archive."
            break
        fi

        [ -d "${APP_HOME}" ] && RM_DIRS "${APP_HOME}"
        MV "${HEADPHONES_SRC_DIR}" "${APP_HOME}" || break
        echo "${HEADPHONES_VERSION}" > "${APP_HOME}/version.id"
        echo "${HEADPHONES_VERSION}" > "${APP_HOME}/version.txt"
        CHOWN_DIR root:root "${APP_HOME}" || break
    fi

    MKDIR "${APP_DIRECTORY}" || break
    APP_DAEMON_PORT="$(( USERUID + DAEMON_PORT - FIRST_UID ))"
    HEADPHONES_URL_BASE="headphones"
    [ "${USERUID}" != "${FIRST_UID}" ] && HEADPHONES_URL_BASE="headphones-${USERNAME}"

    if [ ! -f "${APP_CONFIG}" ] ; then
        cat <<-EOF > "${APP_CONFIG}" 2>> "${LOGFILE}"
		[General]
		EOF
    fi
    RUN_LOG "crudini --set '${APP_CONFIG}' General http_host '127.0.0.1'" || break
    RUN_LOG "crudini --set '${APP_CONFIG}' General http_port '${APP_DAEMON_PORT}'" || break
    RUN_LOG "crudini --set '${APP_CONFIG}' General http_root '/${HEADPHONES_URL_BASE}'" || break
    RUN_LOG "crudini --set '${APP_CONFIG}' General launch_browser '0'" || break
    RUN_LOG "crudini --set '${APP_CONFIG}' General check_github '0'" || break
    RUN_LOG "crudini --set '${APP_CONFIG}' General check_github_on_startup '0'" || break
    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}" || break
    CHOWN_FILE "${USERNAME}":"${USERNAME}" "${APP_CONFIG}" || break

    cat <<-EOF > "/etc/systemd/system/headphones@.service" 2>> "${LOGFILE}"
	[Unit]
	Description=Headphones - Automatic music downloader for SABnzbd
	Wants=network-online.target
	After=network-online.target

	[Service]
	ExecStart=/usr/bin/python3 ${APP_HOME}/Headphones.py --daemon --config /home/%i/.headphones/config.ini --datadir /home/%i/.headphones --nolaunch --quiet
	GuessMainPID=no
	Type=forking
	User=%i
	Group=%i
	Restart=on-failure
	RestartSec=5

	[Install]
	WantedBy=multi-user.target
	EOF

    SYSTEMD_RELOAD
    SVC_ENABLE "headphones@${USERNAME}" || break
    SVC_START  "headphones@${USERNAME}" || break

    if [ -d "/etc/apache2/userconf-enabled" ] ; then
        cat <<-EOF > "/etc/apache2/userconf-enabled/headphones-${USERNAME}.conf" 2>> "${LOGFILE}"
	RewriteEngine on
	RewriteRule ^/${HEADPHONES_URL_BASE}$ /${HEADPHONES_URL_BASE}/ [R=permanent]

	ProxyPreserveHost on
	ProxyPass /${HEADPHONES_URL_BASE} http://127.0.0.1:${APP_DAEMON_PORT}/${HEADPHONES_URL_BASE} connectiontimeout=5 timeout=300
	ProxyPassReverse /${HEADPHONES_URL_BASE} http://127.0.0.1:${APP_DAEMON_PORT}/${HEADPHONES_URL_BASE}

	RequestHeader set "X-Forwarded-Proto" expr=%{REQUEST_SCHEME}
	RequestHeader set "X-Forwarded-SSL" expr=%{HTTPS}

	<Location /${HEADPHONES_URL_BASE}>
	    Order deny,allow
	    Deny from all
	    Allow from all
	    AuthType Digest
	    AuthName "apache2"
	    AuthDigestProvider file
	    AuthUserFile "/etc/apache2/users.password"
	    Require user ${USERNAME}
	</Location>
	EOF
        SVC_RELOAD "apache2"
    fi


    main_rc=0
    break

done


# Cleanup if error
if [ "${main_rc}" -ne 0 ] && [ "${main_rc}" -ne 111 ] && [ "${main_rc}" -ne 117 ] ; then
    SVC_DISABLE "headphones@${USERNAME}"
    SVC_STOP    "headphones@${USERNAME}"
    RM_FILES "/etc/apache2/userconf-enabled/headphones-${USERNAME}.conf"
    RM_FILES "${APP_CONFIG}"
    RM_DIRS "${APP_DIRECTORY}"
    ret="$( find /home -mindepth 2 -maxdepth 2 -type d -name ".headphones" )"
    if [ -z "${ret}" ] ; then
        RM_FILES "/etc/systemd/system/headphones@.service"
        RM_DIRS "${APP_HOME}"
    fi
    SYSTEMD_RELOAD
fi

SCRIPTEXIT
