#!/bin/bash

SCRIPT_VER="1.2"

APP="Subsonic"
APP_CATEGORY="Streaming"
APP_SCOPE="system"
APP_ENABLED="yes"
SUPPORTED_ON="Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="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

    case "${LSB_VENDOR}" in
      "Ubuntu")
          APT_INSTALL "openjdk-8-jre-headless" || break
          ;;
    esac

    WGET "${SUPPORT}/subsonic/subsonic-6.1.6.deb" "${TMP_DIR}/subsonic.deb" || break
    DPKG_INSTALL "${TMP_DIR}/subsonic.deb" || break

    # Configure `subsonic` service
    SVC_STOP  "subsonic"
    RM_DIRS "/var/subsonic"
    RUN_LOG 'sed -i '\''s|^SUBSONIC_ARGS="\(.*\)"|SUBSONIC_ARGS="\1 --host=127.0.0.1 --context-path=/subsonic"|g'\'' /etc/default/subsonic'
    cat <<-EOF >> "/etc/default/subsonic"


	export JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64"
	EOF
    SVC_START "subsonic"

    # Configure `apache2` service
    if [ -d "/etc/apache2/userconf-enabled/" ] ; then
        cat <<-EOF > "/etc/apache2/userconf-enabled/subsonic.conf"
	RewriteEngine on
	RewriteRule ^/subsonic\$ /subsonic/ [R=permanent]
	ProxyRequests off
	<Location /subsonic/>
	   ProxyPreserveHost Off
	   RequestHeader unset Accept-Encoding
	   ProxyPass http://127.0.0.1:4040/subsonic/
	   ProxyPassReverse http://127.0.0.1:4040/subsonic/
	   Order Allow,Deny
	   Allow from All
	</Location>
	EOF
        RUN_LOG "apachectl -t" || break
        SVC_RESTART "${APACHE_SVC}"
    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}': Starting cleanup procedure"
    SVC_DISABLE "subsonic"
    SVC_STOP  "subsonic"
    if [ -e "/etc/apache2/userconf-enabled/subsonic.conf" ] ; then
        RM_FILES "/etc/apache2/userconf-enabled/subsonic.conf"
        SVC_RESTART "${APACHE_SVC}"
    fi
    RM_FILES "/etc/default/subsonic"
    DPKG_REMOVE  "subsonic"
    APT_AUTOREMOVE
fi

SCRIPTEXIT
