#!/bin/bash

#
# Name:		reset-plex
# Version:      1.0.1
#
# (c) 2016-2020, Rapidseedbox, alexey@rapidseedbox.com
#

SC_NAME="$( basename "${0}" )"
_VER="$( grep -m 1 -E '^#\s*Version:\s+' "${0}" | awk '{print $NF}' )"
DIALOG_OPTS="--ascii-lines --no-collapse --colors"
PLEX_CONFIG="/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Preferences.xml"

# TERM dimensions
max_lines="$( tput lines )"
max_lines="$(( max_lines - 3 ))"
max_columns="$( tput cols )"

_usage() {
    cat <<-EOF
	Cleanup Plex Media Server configuration.

	Usage:
	    ${SC_NAME} [-h | --help] [-f]

	    -h | --help    - Show usage information.
	    -f             - Force operation. Don't ask for confirmation.
	EOF
}

#
# Echo the backtitle string in form 'Backtitle ... spaces ... [_VER]'
_backtitle () {
    local v_len
    local t_len
    local n_spaces
    local title

    title="${SC_NAME}: ${1}"

    t_len="$( echo "${title}" | wc -c )"
    v_len="$( echo "${_VER}" | wc -c )"
    n_spaces="$(( max_columns - t_len - v_len ))"

    printf "%s%${n_spaces}s%s" "${title}" " " "${_VER}"
}

FORCE="no"
case "${1}" in
  "-h"|"--help")
      _usage
      exit 0
      ;;
  "-f")
      FORCE="yes"
      ;;
esac

if [ "${FORCE}" != "yes" ] ; then
    if ! dialog ${DIALOG_OPTS} \
            --backtitle "$( _backtitle "Cleanup Plex Media Server configuration" )"    \
            --yesno "Are you sure you want to reset Plex Media Server configuration ?" \
            0 0
    then
        clear
        exit 0
    fi
fi

if [ -f "/etc/monit/conf.d/plexmediaserver" ] ; then
    mv -f "/etc/monit/conf.d/plexmediaserver" /tmp/ > /dev/null 2>&1
    monit reload > /dev/null 2>&1
fi

need_restart_plex="no"
if systemctl is-active "plexmediaserver" > /dev/null 2>&1 ; then
    systemctl stop "plexmediaserver" > /dev/null 2>&1
    need_restart_plex="yes"
fi

cat <<EOF > "${PLEX_CONFIG}"
<?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 600 "${PLEX_CONFIG}" > /dev/null 2>&1
chown plex:plex "${PLEX_CONFIG}" > /dev/null 2>&1

if [ "${need_restart_plex}" = "yes" ] ; then
    systemctl start "plexmediaserver" > /dev/null 2>&1
fi

if [ -f "/tmp/plexmediaserver" ] ; then
    mv -f "/tmp/plexmediaserver" /etc/monit/conf.d/ > /dev/null 2>&1
    monit reload > /dev/null 2>&1
fi

if [ "${FORCE}" != "yes" ] ; then
    clear
fi

exit 0
