#!/bin/bash

SCRIPT_VER="1.8"

APP="Lidarr"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="user"
#><#APP_CHECK_VER_CMD="[ -e "/opt/Lidarr/version.id" ] && cat "/opt/Lidarr/version.id" || echo """
SUPPORTED_ON="Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="yes"
DAEMON_PORT=8686
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}
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}/.config/lidarr"
APP_HOME="/opt/Lidarr"

while : ; do

    main_rc=1

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

    [ -d "${USERHOME}" ] || break

    # -- Install reuired packeges
    APT_INSTALL "gnupg" "ca-certificates" "curl" "sqlite3" "libchromaprint-tools" \
        || break

    case "${LSB_VER}" in
      "Ubuntu22.04")
          # -- Let's try to use official repositories ...
          ;;
      *)
          # -- Install `mono` repository
          RUN_LOG "apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 \
                               --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF" \
              || break
          echo "deb [arch=amd64] https://download.mono-project.com/repo/ubuntu stable-${LSB_CODENAME} main" \
              > "/etc/apt/sources.list.d/mono-official-stable.list"

          # -- Get MediaInfo
          WGET "https://mediaarea.net/repo/deb/repo-mediaarea_1.0-25_all.deb" || break
          DPKG_INSTALL "${TMP_DIR}/repo-mediaarea_1.0-25_all.deb" || break
          ;;
    esac

    #
    # https://github.com/Lidarr/Lidarr
    #

#    # Install dependencies:
#    APT_INSTALL "libmono-cil-dev" "mediainfo" || break

    if [ ! -e "${APP_HOME}/version.id" ] ; then
        if [ -d "${APP_HOME}" ] ; then
            RM_DIRS "${APP_HOME}"
        fi
        INFO "Installing ${APP} into ${APP_HOME}"
        _ver="2.14.5.4836"
        if [ -z "${_ver}" ] ; then
            ERROR "Failed to retrieve ${APP} release tarball URL !"
            break
        else
            APP_URL="https://github.com/Lidarr/Lidarr/releases/download/v${_ver}/Lidarr.master.${_ver}.linux-core-x64.tar.gz"
            INFO "${APP} release tarball URL: ${APP_URL}"
        fi
        if [ -z "${APP_URL}" ] ; then
            ERROR "Failed to parse ${APP} release tarball URL !"
            break
        else
            APP_ARCHIVE=$( echo "${APP_URL}" | awk -F "/" '{print $NF}' )
            INFO "${APP} release tarball: ${APP_ARCHIVE}"
        fi
        WGET "${APP_URL}" || break
        TAR_ZXF "${TMP_DIR}/${APP_ARCHIVE}" "/opt/" || break
        echo "${_ver}" > "${APP_HOME}/version.id"
        CHOWN_DIR root:root "${APP_HOME}" || break
        RUN_LOG "find ${APP_HOME} -type d -exec chmod 755 {} \;"
        RUN_LOG "find ${APP_HOME} -type f -exec chmod 755 {} \;"
    fi

    MKDIR "${APP_DIRECTORY}" || break
    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}" || break
 
    APP_DAEMON_PORT="$(( USERUID + 8686 - FIRST_UID ))"

    cat <<-EOF > "/etc/systemd/system/${APP,,}@.service"
	[Unit]
	Description=${APP} Daemon
	After=syslog.target network.target

	[Service]
	User=%i
	Group=%i
	Type=simple
	ExecStart=/opt/Lidarr/Lidarr -nobrowser -data=/home/%i/.config/lidarr
	TimeoutStopSec=20
	KillMode=process
	Restart=on-failure

	[Install]
	WantedBy=multi-user.target
	EOF

    cat <<-EOF > "/etc/systemd/system/${APP,,}.slice" 2>> "${LOGFILE}"
	[Unit]
	Description=${APP} resource limiting
	Before=slices.target

	[Slice]
	CPUAccounting=yes
	CPUQuota=20%
	IOAccounting=yes
	IOReadBandwidthMax=/ 20M
	IOWriteBandwidthMax=/ 20M
	EOF

    [ ! -d "/etc/systemd/system/${APP,,}@.service.d" ] \
        && MKDIR "/etc/systemd/system/${APP,,}@.service.d"

    cat <<-EOF > "/etc/systemd/system/${APP,,}@.service.d/001-Slice.conf"
	[Service]
	Slice=${APP,,}.slice
	EOF

    SYSTEMD_RELOAD

    if [ "${USERUID}" = "${FIRST_UID}" ] ; then
        cat <<-EOF > "${APP_DIRECTORY}/config.xml"
		<Config>
		  <Port>${APP_DAEMON_PORT}</Port>
		  <BindAddress>127.0.0.1</BindAddress>
		  <UrlBase>lidarr</UrlBase>
		  <EnableSsl>False</EnableSsl>
		  <LaunchBrowser>False</LaunchBrowser>
		  <UpdateAutomatically>False</UpdateAutomatically>
		  <AuthenticationMethod>External</AuthenticationMethod>
		</Config>
	EOF
    else
        cat <<-EOF > "${APP_DIRECTORY}/config.xml"
		<Config>
		  <Port>${APP_DAEMON_PORT}</Port>
		  <BindAddress>127.0.0.1</BindAddress>
		  <UrlBase>lidarr-${USERNAME}</UrlBase>
		  <EnableSsl>False</EnableSsl>
		  <LaunchBrowser>False</LaunchBrowser>
		  <UpdateAutomatically>False</UpdateAutomatically>
		  <AuthenticationMethod>External</AuthenticationMethod>
		</Config>
	EOF
    fi
    CHOWN_FILE "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}/config.xml" || break

    SVC_ENABLE "${APP,,}@${USERNAME}" || break
    SVC_START  "${APP,,}@${USERNAME}" || break

    # Configure Apache
    if [ -d "/etc/apache2/userconf-enabled" ] ; then
        [ -e "/etc/apache2/userconf-enabled/${APP,,}-${USERNAME}.conf" ] \
            && RM_FILES "/etc/apache2/userconf-enabled/${APP,,}-${USERNAME}.conf"
        if [ "${USERUID}" = "${FIRST_UID}" ] ; then
            cat <<-EOF > "/etc/apache2/userconf-enabled/${APP,,}-${USERNAME}.conf" 2>> "${LOGFILE}"
		RewriteEngine on
		RewriteRule ^/lidarr$ /lidarr/ [R=permanent]
		ProxyPreserveHost on
		ProxyPass /lidarr http://localhost:${APP_DAEMON_PORT}/lidarr connectiontimeout=5 timeout=300
		ProxyPassReverse /lidarr http://localhost:${APP_DAEMON_PORT}/lidarr

		<Location /lidarr>
		    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
        else
            cat <<-EOF >> "/etc/apache2/userconf-enabled/${APP,,}-${USERNAME}.conf" 2>> "${LOGFILE}"
		RewriteEngine on
		RewriteRule ^/lidarr-${USERNAME}$ /${APP,,}-${USERNAME}/ [R=permanent]
		ProxyPreserveHost on
		ProxyPass /lidarr-${USERNAME} http://localhost:${APP_DAEMON_PORT}/lidarr-${USERNAME} connectiontimeout=5 timeout=300
		ProxyPassReverse /lidarr-${USERNAME} http://localhost:${APP_DAEMON_PORT}/lidarr-${USERNAME}

		<Location /lidarr-${USERNAME}>
		    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
        fi
        SVC_RELOAD "apache2"
    fi


    main_rc=0
    break

done


SCRIPTEXIT
