#!/bin/bash

SCRIPT_VER="1.10"

APP="Sonarr"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="user"
#><#APP_UPGRADE_VER_CMD="STANDARD_PACKAGE"
SUPPORTED_ON="Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="yes"
DAEMON_PORT=8989
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://wiki.servarr.com/sonarr/installation
# https://gist.github.com/pettazz/e979cce035c364adf5008faa61a24aac

#APP_DIRECTORY="/var/lib/sonarr"
APP_DIRECTORY="${USERHOME}/.config/sonarr"

while : ; do

    main_rc=1 

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


    # -- Install required packages
    APT_INSTALL "gnupg" "ca-certificates" || break

    case "${LSB_VER}" in
      "Ubuntu22.04")
          # -- Will use Ubuntu 20.04 repository
          RUN_LOG "gpg --no-default-keyring \
                       --keyring /usr/share/keyrings/sonarr.gpg \
                       --keyserver hkp://keyserver.ubuntu.com:80 \
                       --recv-keys EBFF6B99D9B78493" \
              || break
          echo 'deb [signed-by=/usr/share/keyrings/sonarr.gpg] https://apt.sonarr.tv/ubuntu focal main' \
                    > "/etc/apt/sources.list.d/sonarr.list"
          ;;
      *)
          # -- 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

          # -- Add the Sonarr Repo
          RUN_LOG "apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 \
                               --recv-keys 2009837CBFFD68F45BC180471F4F90DE2A9B4BF8" || break
          RUN_LOG "echo 'deb https://apt.sonarr.tv/ubuntu ${LSB_CODENAME} main' \
                             > /etc/apt/sources.list.d/sonarr.list" || break
          ;;
    esac

    APT_UPDATE || break

    # -- Install Sonarr & Mediainfo
    APT_INSTALL "sonarr" "mediainfo" || break

    # -- Stop / disable / mask "default" `sonarr` service
    SVC_STOP "sonarr"
    SVC_DISABLE "sonarr"
    SVC_MASK "sonarr"

    # -- Update SSL certificates
    RUN_LOG "cert-sync /etc/ssl/certs/ca-certificates.crt" || break

    # -- Configure `sonarr` application instance

    SONARR_DAEMON_PORT="$(( USERUID + 8989 - FIRST_UID ))"

    MKDIR "${APP_DIRECTORY}" || break

    SONARR_SUBDIR="sonarr"
    [ "${USERUID}" != "${FIRST_UID}" ] \
        && SONARR_SUBDIR="${SONARR_SUBDIR}-${USERNAME}"

    cat <<-EOF > "${APP_DIRECTORY}/config.xml"
	<Config>
	  <LogLevel>info</LogLevel>
	  <EnableSsl>False</EnableSsl>
	  <Port>${SONARR_DAEMON_PORT}</Port>
	  <UrlBase>${SONARR_SUBDIR}</UrlBase>
	  <BindAddress>127.0.0.1</BindAddress>
	  <AuthenticationMethod>None</AuthenticationMethod>
	  <UpdateMechanism>BuiltIn</UpdateMechanism>
	  <Branch>main</Branch>
	</Config>
	EOF

    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}" || break

    # -- Configure `sonarr` service
    cat <<-EOF > "/etc/systemd/system/sonarr.slice"
	[Unit]
	Description=${APP} resource limiting
	Before=slices.target

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

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

	[Service]
	User=%i
	Group=%i
	UMask=0002
	Type=simple
	ExecStart=/usr/bin/mono --debug /usr/lib/sonarr/bin/Sonarr.exe -nobrowser -data=/home/%i/.config/sonarr
	TimeoutStopSec=20
	KillMode=process
	Restart=on-failure

	[Install]
	WantedBy=multi-user.target
	EOF

    [ ! -d "/etc/systemd/system/sonarr@.service.d" ] \
        && MKDIR "/etc/systemd/system/sonarr@.service.d"

    cat <<-EOF > "/etc/systemd/system/sonarr@.service.d/001-Slice.conf"
	[Service]
	Slice=sonarr.slice
	EOF

    SYSTEMD_RELOAD

    # -- Enable / restart `sonarr` service
    SVC_ENABLE  "sonarr@${USERNAME}"
    SVC_RESTART "sonarr@${USERNAME}"

    # -- Configure Apache2 reverse proxy
    RM_FILES "/etc/apache2/userconf-enabled/sonarr.conf" \
             "/etc/apache2/userconf-available/sonarr.conf"
    cat <<-EOF > "/etc/apache2/userconf-enabled/sonarr-${USERNAME}.conf"
	RewriteEngine on
	RewriteRule ^/${SONARR_SUBDIR}$ /${SONARR_SUBDIR}/ [R=permanent]
	ProxyPreserveHost on
	ProxyPass /${SONARR_SUBDIR} http://localhost:${SONARR_DAEMON_PORT}/${SONARR_SUBDIR} connectiontimeout=5 timeout=300
	ProxyPassReverse /${SONARR_SUBDIR} http://localhost:${SONARR_DAEMON_PORT}/${SONARR_SUBDIR}


	<Location /${SONARR_SUBDIR}>
	    Order Allow,Deny
	    Allow from All
	    AuthType Digest
	    AuthName "apache2"
	    AuthDigestProvider file
	    AuthUserFile "/etc/apache2/users.password"
	    Require user ${USERNAME}
	</Location>
	EOF

    # -- Restart `apache2` service
    SVC_RESTART "apache2"


    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
    SVC_DISABLE "sonarr"
    SVC_STOP    "sonarr"
    SVC_MASK    "sonarr"
    SVC_DISABLE "sonarr@${USERNAME}"
    SVC_STOP    "sonarr@${USERNAME}"
    SYSTEMD_RELOAD
#    APT_REMOVE "sonarr"
#    RM_FILES "/etc/apt/sources.list.d/sonarr.list"
#    APT_UPDATE
#    RUN_LOG "userdel -f -r sonarr"
fi

SCRIPTEXIT
