#!/bin/bash

SCRIPT_VER="1.11"

APP="Plex"
APP_CATEGORY="Streaming"
APP_SCOPE="system"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="plex"
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04,Ubuntu24.04"
MEMORY_K_MIN="4000000"
USE_APACHE2="yes"
LIBRARY="functions4.sh"

PMS_CFG_USER="user"
PMS_CFG_PASS="ChangeMe"

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


APP_HOME="/var/lib/plexmediaserver"
APP_DIRECTORY="${APP_HOME}/Library/Application Support/Plex Media Server"

while : ; do

    main_rc=1

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


    if ! RUN_LOG "getent group video 2>&1" ; then
        RUN_LOG "groupadd --system video 2>&1" || break
    fi

    # Remove legacy repository if exists
    [ -f "/etc/apt/sources.list.d/plexmediaserver.list" ] && RM_FILES "/etc/apt/sources.list.d/plexmediaserver.list"

    ADD_APT_REPO "https://repo.plex.tv/deb" "public" "main" "https://downloads.plex.tv/plex-keys/PlexSign.v2.key" "plex" || break

    APT_UPDATE || break
    APT_INSTALL "plexmediaserver" || break
    [ -e "plexmediaserver*.deb.sha" ] \
        && RM_FILES "plexmediaserver*.deb.sha"


    [ "${SVC_SYSTEM}" = "systemd" ] \
        && SYSTEMD_RELOAD
    # Configure services
    SVC_ENABLE "plexmediaserver"
    RUN_LOG "/usr/sbin/service plexmediaserver status 2>&1"
    if [ $? -ne 0 ] ; then
         SVC_START "plexmediaserver"
         INFO "Sleeping for 10 seconds..."
         sleep 10
         LL_LOG
    fi
    SVC_STATUS "plexmediaserver" \
        && SVC_STOP "plexmediaserver"


    # ---------------------------------------------------
    # Configure Apache
    # ---------------------------------------------------
    if [ -e "/etc/apache2" ] ; then
        passwd_file="/etc/apache2/plex.users.password"
        apache_log_dir="\${APACHE_LOG_DIR}"
        [ "${LSB_VENDOR}" = "CentOS" ] \
            && apache_log_dir="logs"
        cat <<-EOF > "/etc/apache2/sites-available/plex.conf"
	Listen 33400

	<VirtualHost *:33400>

	        ServerAdmin plexguru@plex.rapidseedbox.com
	        ErrorLog ${apache_log_dir}/plex-error.log
	        CustomLog ${apache_log_dir}/plex-access.log combined

	        Header add referer "http://127.0.0.1"
	        RequestHeader set referer "http://127.0.0.1"
	        RequestHeader set X-Forwarded-For 127.0.0.1

	        ProxyPass / http://127.0.0.1:32400/
	        ProxyPassReverse / http://127.0.0.1:32400/

	        <Proxy *>
	            AuthType Digest
	            AuthName "apache2"
	            AuthUserFile ${passwd_file}
	            Require user ${PMS_CFG_USER}
	        </Proxy>

	        RewriteEngine on
	        RewriteCond %{REQUEST_URI} !^/web
	        RewriteCond %{HTTP:X-Plex-Device} ^\$
	        RewriteCond %{QUERY_STRING} (^|&)X-Plex-Device=(&|\$) [OR]
	        RewriteCond %{QUERY_STRING} !(^|&)X-Plex-Device=
	        RewriteRule ^/\$ /web/\$1 [R,L]

	</VirtualHost>
	EOF
        pline="$( (echo -n "${PMS_CFG_USER}:apache2:" && echo -n "${PMS_CFG_USER}:apache2:${PMS_CFG_PASS}" | md5sum | awk '{print $1}') )"
        if [ -e "${passwd_file}" ] ; then
            if RUN_LOG "grep -e '^${PMS_CFG_USER}:apache2:' '${passwd_file}'" ; then
                RUN_LOG "sed -f 's|^${PMS_CFG_USER}:apache2:.*|${pline}|' -i '${passwd_file}'"
            else
                RUN_LOG "echo '${pline}' >> '${passwd_file}'"
            fi
        else
            RUN_LOG "echo '${pline}' > '${passwd_file}'"
        fi

        if [ "${LSB_VENDOR}" = "Debian" -o "${LSB_VENDOR}" = "Ubuntu" ] ; then
            RUN_LOG "a2ensite plex.conf"
            RUN_LOG "a2enmod proxy"
            RUN_LOG "a2enmod proxy_http"
            RUN_LOG "a2enmod headers"
            RUN_LOG "a2enmod rewrite"
        fi

#        if [ -d "/etc/apache2/userconf-enabled" ] ; then
#            cat <<-'EOF' > "/etc/apache2/userconf-enabled/plex.conf"
#		<IfModule mod_proxy.c>
#		    <Proxy *>
#		        Order deny,allow
#		        Allow from all
#		    </Proxy>
#
#		    ProxyRequests off
#		    ProxyPreserveHost On
#
#		    ProxyPass / http://127.0.0.1:32400/
#		    ProxyPassReverse / http://127.0.0.1:32400/
#
#		    RewriteEngine on
#		    RewriteCond %{REQUEST_URI} !^/web
#		    RewriteCond %{HTTP:X-Plex-Device} ^$
#		    RewriteRule ^/$ /web/$1 [R,L]
#		</IfModule>
#		EOF
#            cat <<-'EOF' > "/etc/apache2/userconf-enabled/plex.conf"
#		<IfModule mod_proxy.c>
#
#		    <Proxy *>
#		        Order deny,allow
#		        Allow from all
#		    </Proxy>
#
#		    ProxyRequests off
#		    ProxyPreserveHost On
#
#		    ProxyPass / http://127.0.0.1:32400/
#		    ProxyPassReverse / http://127.0.0.1:32400/
#
#		</IfModule>
#		EOF
#        fi

        SVC_RESTART  "${APACHE_SVC}"

    fi

    # ---------------------------------------------------
    # Configure Plex
    # ---------------------------------------------------

    INFO "Starting '${APP}' post-install configuration"

    __plex_prefs="${APP_DIRECTORY}/Preferences.xml"

    cat <<-EOF > "${__plex_prefs}"
	<?xml version="1.0" encoding="utf-8"?>
	<Preferences allowedNetworks="127.0.0.1/255.255.255.255" AcceptedEULA="1" FriendlyName="plex.rapidseedbox.com" ManualPortMappingMode="1" ManualPortMappingPort="32400" PublishServerOnPlexOnlineKey="1"/>
	EOF
    CHMOD_FILE 600 "${__plex_prefs}"
    CHOWN_FILE plex:plex "${__plex_prefs}"

    SVC_START "plexmediaserver"

    INFO "Finished '${APP}' post-install configuration"

    if [ -d "/etc/monit/conf.d" ] ; then
        cat <<-EOF > "/etc/monit/conf.d/plexmediaserver"
	check process plexmediaserver with pidfile "${APP_DIRECTORY}/plexmediaserver.pid"
	  start program = "/usr/sbin/service plexmediaserver restart"
	  stop program = "/usr/sbin/service plexmediaserver stop"
	  if 5 restarts with 5 cycles then timeout
	EOF
        MONIT_RELOAD
    fi

    # 'claim-plex' script - TBD !!!

    # 'reset-plex' script
    cat <<-EOF > "/usr/local/bin/reset-plex"
	#!/bin/sh

	if [ -f "/etc/monit/conf.d/plexmediaserver" ] ; then
	    mv -fv "/etc/monit/conf.d/plexmediaserver" /tmp/
	    monit reload
	fi

	service plexmediaserver stop

	echo '<?xml version="1.0" encoding="utf-8"?>' > "/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Preferences.xml"
	echo '<Preferences allowedNetworks="127.0.0.1/255.255.255.255" AcceptedEULA="1" FriendlyName="plex.rapidseedbox.com" ManualPortMappingMode="1" ManualPortMappingPort="32400" PublishServerOnPlexOnlineKey="1"/>' >> "/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Preferences.xml"
	chmod 600 "/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Preferences.xml"
	chown plex:plex "/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Preferences.xml"

	service plexmediaserver start

	if [ -f "/tmp/plexmediaserver" ] ; then
	    mv -fv "/tmp/plexmediaserver" /etc/monit/conf.d/
	    monit reload
	fi
	EOF
    CHMOD_FILE 0755 "/usr/local/bin/reset-plex"
    LN "/usr/local/bin/reset-plex" "/usr/local/bin/rsb-reset-plex"

    # -- Allow `plex` group & user account to write to user's Downloads directory
    RUN_LOG "setfacl -Rm g:plex:rwX,d:g:plex:rwX /etc/skel/Downloads   2>&1"
    RUN_LOG "setfacl -Rm g:plex:rwX,d:g:plex:rwX /home/user/Downloads  2>&1"
    RUN_LOG "setfacl -Rm g:plex:rwX,d:g:plex:rwX ${USERHOME}/Downloads 2>&1"

    # -- NGv1.5 / NGv3 customizations
    if mountpoint "/data" > /dev/null ; then
        # ---- Stop `plexmediaserver` if necessary
        _need_restart="no"
        if systemctl is-active "plexmediaserver" > /dev/null 2>&1 ; then
            SVC_STOP "plexmediaserver"
            _need_restart="yes"
        fi
        # ---- Move PLEX directory
        [ -d "/data/apps.data" ] || MKDIR "/data/apps.data"
        RUN_LOG "mv -vf '${APP_DIRECTORY}' /data/apps.data/ 2>&1"
        RM_DIRS "${APP_DIRECTORY}"
        # ---- Create symlink
        RUN_LOG "ln -svf '/data/apps.data/Plex Media Server' '${APP_DIRECTORY}' 2>&1"
        # ---- Restart `plexmediaserver` if necessary
        if [ "${_need_restart}" = "yes" ] ; then
            SVC_START "plexmediaserver"
        fi
    fi


    main_rc=0
    break

done


SCRIPTEXIT
