#!/bin/bash

SCRIPT_VER="1.3"

APP="PlexPy"
APP_CATEGORY="Streaming"
APP_SCOPE="system"
APP_ENABLED="yes"
#><#APP_CHECK_VER_CMD="if [ -e /opt/plexpy/CHANGELOG.md ] ; then grep -m 1 -e "^## " /opt/plexpy/CHANGELOG.md | awk "{print \$2}" ; else echo "" ; fi"
##><#APP_UPGRADE_VER_CMD="wget -S --timeout=10 --tries=3 -vvv --spider https://github.com/Tautulli/Tautulli/tarball/master 2>&1 | grep filename= | awk "{print \$3}" | sed -e "s/filename=Tautulli-Tautulli-\(.*\)\.tar\.gz/\1/" | sed "s/\(.*\)-.*/\1/" | tr "-" "_""
DEPENDS="Plex"
CONFLICTS="Tautulli"
SUPPORTED_ON="Debian9,Debian10,Ubuntu16.04,Ubuntu18.04,Ubuntu20.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


PLEXPY_USER="plexpy"
APP_DIRECTORY="/opt/plexpy"

while : ; do

    main_rc=1

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

    ${PKG_INSTALL} "git-core" || break

    oWD=$( pwd )
    cd "${APP_DIRECTORY}" || break
    if [ ! -d "./.git" ] ; then
        RUN_LOG "git init" || break
        RUN_LOG "git config --global user.email 'user@example.com'" || break
        RUN_LOG "git config --global user.name 'Seedbox Admin'" || break
        RUN_LOG "git add ." || break
        RUN_LOG "git commit -m'RSB: initial commit'" || break
        RUN_LOG "git clean -f" || break
        RUN_LOG "git remote add origin 'https://github.com/drzoidberg33/plexpy.git'" || break
    fi
    RUN_LOG "git fetch --all" || break
    RUN_LOG "git reset --hard origin/master" || break
    RUN_LOG "git pull --no-edit origin master -f" || break
    cd "${oWD}"

    CHOWN_DIR ${PLEXPY_USER}:${PLEXPY_USER} "${APP_DIRECTORY}"

    SVC_STATUS  "plexpy" \
        && SVC_RESTART  "plexpy"


    main_rc=0
    break

done


SCRIPTEXIT
