#!/usr/bin/with-contenv bash

# This file contains part of the official PLEX 40-plex-first-run
# Here: https://github.com/plexinc/pms-docker/blob/master/root/etc/cont-init.d/40-plex-first-run
# It should live in /etc/cont-init.d/

# If we are debugging, enable trace
if [ "${DEBUG,,}" = "true" ]; then
  set -x
fi

function setPref {
  local key="$1"
  local value="$2"

  count="$(xmlstarlet sel -t -v "count(/Preferences/@${key})" "${prefFile}")"
  count=$(($count + 0))
  if [[ $count > 0 ]]; then
    xmlstarlet ed --inplace --update "/Preferences/@${key}" -v "${value}" "${prefFile}"
  else
    xmlstarlet ed --inplace --insert "/Preferences"  --type attr -n "${key}" -v "${value}" "${prefFile}"
  fi
}

home="$(echo ~plex)"
pmsApplicationSupportDir="${PLEX_MEDIA_SERVER_APPLICATION_SUPPORT_DIR:-${home}/Library/Application Support}"
prefFile="${pmsApplicationSupportDir}/Plex Media Server/Preferences.xml"

# If PKCSMANGLER__PFXINCONTAINERPATH is set, then assume we want to move the PFX Cert to that location
if [ ! -z "${PKCSMANGLER_PFXINCONTAINERPATH}" ]; then
  # If it ends up a problem, we may need to set some kind of "don't replace existing PFX cert"
  cp -f /shared/cert.pfx "${PKCSMANGLER_PFXINCONTAINERPATH}"
  # If PKCSMANGLER__CUSTOMCERTDOMAIN is set, then assume we want to set the PLEX Preference customCertificatePath because we enabled setting PLEX Preferences
  if [ ! -z "${PKCSMANGLER_CUSTOMCERTDOMAIN}" ]; then
    setPref "customCertificatePath" "${PKCSMANGLER_PFXINCONTAINERPATH}"
  fi
fi

# If PKCSMANGLER_PFXPASSWORD is set, then assume we want to set the PLEX Preference customCertificateKey
if [ ! -z "${PKCSMANGLER_PFXPASSWORD}" ]; then
  setPref "customCertificateKey" "${PKCSMANGLER_PFXPASSWORD}"
fi

# If PKCSMANGLER__CUSTOMCERTDOMAIN is set, then assume we want to set the PLEX Preference customCertificateDomain
if [ ! -z "${PKCSMANGLER_CUSTOMCERTDOMAIN}" ]; then
  PreferenceValue=${PKCSMANGLER_CUSTOMCERTDOMAIN#*=}
  PreferenceKey=${PKCSMANGLER_CUSTOMCERTDOMAIN%=*}
  setPref $PreferenceKey $PreferenceValue
fi

# touch /.firstRunComplete
# echo "Plex Media Server first run setup complete"
echo "PKCS Mangler run complete"