#!/bin/bash

SCRIPT_VER="1.4"

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

APP_DIRECTORY="/var/lib/jellyfin"

while : ; do

    main_rc=1 

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

    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    #
    # u22.04 issue
    # * [Issue]: jellyfin have unmet dependencies - Unable to install #7742 *
    # https://github.com/jellyfin/jellyfin/issues/7742
    #
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    case "${LSB_VENDOR}" in
      "Ubuntu")
          MKDIR "/etc/apt/sources.list.d" || break
          echo "deb [arch=$( \
                      dpkg --print-architecture \
                           )] https://repo.jellyfin.org/ubuntu ${LSB_CODENAME} main" \
                    > "/etc/apt/sources.list.d/jellyfin.list"
          if [ $? -ne 0 ] ; then
              ERROR "Error adding Jellyfin repository!"
              break
          fi
          if ! ADD_APT_KEY_URL "https://repo.jellyfin.org/ubuntu/jellyfin_team.gpg.key" "jellyfin_team.gpg"
          then
              ERROR "Error adding Jellyfin repository key!"
              RM_FILES "/etc/apt/sources.list.d/jellyfin.list"
              break
          fi
          APT_UPDATE || break
          APT_INSTALL "jellyfin"
          RUN_LOG "apt-get install -y -f" || break
          ;;
    esac

    if which "relocate-app-data" > /dev/null 2>&1 ; then
        INFO "Sleeping for 10 seconds ..."
        sleep 10
        RUN_LOG "relocate-app-data -a jellyfin 2>&1"
    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
    if [ -e "/etc/apt/sources.list.d/jellyfin.list" ] ; then
        RM_FILES "/etc/apt/sources.list.d/jellyfin.list" \
            && APT_UPDATE
    fi
fi
SCRIPTEXIT
