#!/bin/bash

SCRIPT_VER="1.4"

APP="Plexdrive Service"
APP_CATEGORY="Streaming"
APP_SCOPE="system"
APP_ENABLED="yes"
#><#APP_CHECK_VER_CMD="[ -x /usr/local/bin/plexdrive -a -e /etc/systemd/system/plexdrive.service ] && /usr/local/bin/plexdrive --version"
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04,Ubuntu24.04"
MEMORY_K_MIN="4000000"
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


VALIDATE_USER

APP_HOME="/var/lib/plexmediaserver"
APP_CFG_DIR="${APP_HOME}/.plexdrive"
APP_MOUNT_DIR="${APP_HOME}/plexdrive"

while : ; do

    main_rc=1

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


    if [ "${USERUID}" != "${FIRST_UID}" ] ; then
        ERROR "Cannot install this application for the user account '${USERNAME}'"
        break
    fi

    if ! id plex > /dev/null 2>&1 ; then
        ERROR "'${APP}' requires Plex Media Server to be installed first."
        break
    fi

    ${PKG_INSTALL} "fuse3" || break

    # Install 'plexdrive' binary
    if [ ! -x "/usr/local/bin/plexdrive" ] ; then
        _plexdrive_url="$( GITHUB_RELEASE "plexdrive/plexdrive" "latest" "amd64" "binary" "^plexdrive-linux-amd64$" )" || break
        if [ -z "${_plexdrive_url}" ] ; then
            ERROR "Could not determine ${APP} download URL!"
            break
        fi
        INFO "Latest build: ${GITHUB_RELEASE_TAG}"

        WGET "${_plexdrive_url}" "${TMP_DIR}/plexdrive" || break
        MV "${TMP_DIR}/plexdrive" "/usr/local/bin/plexdrive" || break
        CHOWN_FILE root:root "/usr/local/bin/plexdrive" || break
        CHMOD_FILE 755 "/usr/local/bin/plexdrive" || break
    fi

    # Install 'plexdrive-init' script
    cat <<-'EOF_INIT' > "/usr/local/bin/plexdrive-init"
	#!/bin/sh

	#
	# Name:         plexdrive-init
	# Version:      1.1.0
	#
	# (c) 2017-2020, Rapidseedbox, alexey@rapidseedbox.com
	#

	_VER="$( grep -m 1 -E '^#\s*Version:\s+' "${0}" | awk '{print $NF}' )"
	app_home="/var/lib/plexmediaserver"
	cfg_dir="${app_home}/.plexdrive"
	mount_dir="${app_home}/plexdrive"
	_uid="$( id -u )"
	if [ "${_uid}" -ne 0 ] ; then
	    echo "Sorry."
	    echo "You must run this script as 'root' so it can initialize the Plex-owned Plexdrive configuration."
	    exit 1
	fi

	if ! id plex > /dev/null 2>&1 ; then
	    echo "The 'plex' user does not exist. Install Plex Media Server first."
	    exit 1
	fi

	[ -d "${cfg_dir}" ] || mkdir -p "${cfg_dir}"
	[ -d "${mount_dir}" ] || mkdir -p "${mount_dir}"
	chown plex:plex "${cfg_dir}" "${mount_dir}"
	chmod 750 "${cfg_dir}" "${mount_dir}"

	exec su -s /bin/sh plex -c "/usr/local/bin/plexdrive mount -c ${cfg_dir} -v 2 ${mount_dir}"
	EOF_INIT
    CHMOD_FILE 755 "/usr/local/bin/plexdrive-init" || break
    LN "/usr/local/bin/plexdrive-init" "/usr/local/bin/rsb-plexdrive-init" || break

    # Install 'plexdrive' SystemD unit
    cat <<-EOF_UNIT > "/etc/systemd/system/plexdrive.service"
	[Unit]
	Description=Mount Plexdrive to ${APP_MOUNT_DIR}
	After=network-online.target
	Wants=network-online.target
	AssertPathExists=${APP_CFG_DIR}/config.json

	[Service]
	Type=simple
	User=plex
	Group=plex
	ExecStartPre=-/bin/mkdir -p ${APP_MOUNT_DIR}
	ExecStartPre=-/bin/chown plex:plex ${APP_MOUNT_DIR}
	ExecStartPre=-/bin/chmod 755 ${APP_MOUNT_DIR}
	ExecStart=/usr/local/bin/plexdrive mount \
	  -c ${APP_CFG_DIR} \
	  -v 3 \
	  --refresh-interval=1m \
	  --chunk-check-threads=8 \
	  --chunk-load-threads=8 \
	  --chunk-load-ahead=4 \
	  --max-chunks=100 \
	  --fuse-options=read_only \
	     ${APP_MOUNT_DIR}
	ExecStop=-/bin/fusermount -u -z ${APP_MOUNT_DIR}
	Restart=always
	RestartSec=5

	[Install]
	WantedBy=multi-user.target
	EOF_UNIT

    if [ ! -d "${APP_CFG_DIR}" ] ; then
        MKDIR "${APP_CFG_DIR}" || break
    fi
    CHMOD_DIR 750 "${APP_CFG_DIR}" || break
    CHOWN_DIR plex:plex "${APP_CFG_DIR}" || break

    if [ ! -d "${APP_MOUNT_DIR}" ] ; then
        MKDIR "${APP_MOUNT_DIR}" || break
    fi
    CHMOD_DIR 750 "${APP_MOUNT_DIR}" || break
    CHOWN_DIR plex:plex "${APP_MOUNT_DIR}" || break

    # Enable/Start 'plexdrive' service
    SYSTEMD_RELOAD || break
    SVC_ENABLE "plexdrive" || break
    if [ -e "${APP_CFG_DIR}/config.json" ] ; then
        SVC_START "plexdrive" || break
    else
        INFO "Skipping service start until Plexdrive is initialized with '/usr/local/bin/rsb-plexdrive-init'."
    fi


    main_rc=0
    break

done


# Cleanup if error
if [ "${main_rc}" -ne 0 ] && [ "${main_rc}" -ne 111 ] && [ "${main_rc}" -ne 117 ] ; then
    if [ -e "/etc/systemd/system/plexdrive.service" ] ; then
        SVC_DISABLE "plexdrive"
        SVC_STOP "plexdrive"
        RM_FILES "/etc/systemd/system/plexdrive.service"
        SYSTEMD_RELOAD
    fi
fi

SCRIPTEXIT
