#!/bin/bash

SCRIPT_VER="1.2"

APP="Madsonic"
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 "https://download.madsonic.org/6.2/20190425_madsonic-6.2.9084.deb" \
         "${TMP_DIR}/madsonic.deb" \
      || break
    DPKG_INSTALL "${TMP_DIR}/madsonic.deb" || break

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


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

    # Configure `apache2` service
    if [ -d "/etc/apache2/userconf-enabled/" ] ; then
        cat <<-EOF > "/etc/apache2/userconf-enabled/madsonic.conf"
	RewriteEngine on
	RewriteRule ^/madsonic\$ /madsonic/ [R=permanent]
	ProxyRequests off
	<Location /madsonic/>
	   ProxyPreserveHost Off
	   RequestHeader unset Accept-Encoding
	   ProxyPass http://127.0.0.1:4041/madsonic/
	   ProxyPassReverse http://127.0.0.1:4041/madsonic/
	   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 "madsonic"
    SVC_STOP  "madsonic"
    if [ -e "/etc/apache2/userconf-enabled/madsonic.conf" ] ; then
        RM_FILES "/etc/apache2/userconf-enabled/madsonic.conf"
        SVC_RESTART "${APACHE_SVC}"
    fi
    RM_FILES "/etc/default/madsonic"
    DPKG_REMOVE  "madsonic"
    APT_AUTOREMOVE
fi

SCRIPTEXIT
