#!/bin/bash

#
# Name:		claim-plex
# Version:      1.0.3
#
# (c) 2018-2020,  https://github.com/uglymagoo/plex-claim-server
#                 Rapidseedbox, alexey@rapidseedbox.com
#

SC_NAME="$( basename "${0}" )"
_VER="$( grep -m 1 -E '^#\s*Version:\s+' "${0}" | awk '{print $NF}' )"

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

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

	    -h | --help    - Show usage information.
	    CLAIM_CODE     - Login to https://www.plex.tv/claim/ using your Plex.TV account.
	                     Copy the claim code to the clipboard and use it as an argument.
	EOF
}


if [ -z "${1}" ] ; then
    _usage
    exit 0
fi

case "${1}" in
  "-h"|"--help")
      _usage
      exit 0
      ;;
esac

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

main_rc=0

function getPref {
  local key="$1"
  sed -n -E "s/^.*${key}=\"([^\"]*)\".*$/\1/p" "${prefFile}"
}

function setPref {
  local key="$1"
  local value="$2"
  
  count="$(grep -c "${key}" "${prefFile}")"
  count=$(($count + 0))
  if [[ $count > 0 ]]; then
    sed -i -E "s/${key}=\"([^\"]*)\"/${key}=\"$value\"/" "${prefFile}"
  else
    sed -i -E "s/\/>/ ${key}=\"$value\"\/>/" "${prefFile}"
  fi
}

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

PLEX_CLAIM="${1}"

# Create empty shell pref file if it doesn't exist already
if [ ! -e "${prefFile}" ]; then
  echo "Creating pref shell"
  mkdir -p "$( dirname "${prefFile}" )"
  cat > "${prefFile}" <<-EOF
<?xml version="1.0" encoding="utf-8"?>
<Preferences/>
EOF
  chown -R plex:plex "$( dirname "${prefFile}" )"
fi

# Setup Server's client identifier
serial="$( getPref "MachineIdentifier" )"
if [ -z "${serial}" ]; then
  serial="$( uuidgen )"
  setPref "MachineIdentifier" "${serial}"
fi
clientId="$( getPref "ProcessedMachineIdentifier" )"
if [ -z "${clientId}" ]; then
  clientId="$( echo -n "${serial}- Plex Media Server" | sha1sum | cut -b 1-40 )"
  setPref "ProcessedMachineIdentifier" "${clientId}"
fi

# Get server token and only turn claim token into server token if we have former but not latter.
token="$( getPref "PlexOnlineToken" )"
if [ ! -z "${PLEX_CLAIM}" ] && [ -z "${token}" ]; then
  echo "Attempting to obtain server token from claim token"
  loginInfo="$( curl -X POST \
        -H 'X-Plex-Client-Identifier: '${clientId} \
        -H 'X-Plex-Product: Plex Media Server'\
        -H 'X-Plex-Version: 1.1' \
        -H 'X-Plex-Provides: server' \
        -H 'X-Plex-Platform: Linux' \
        -H 'X-Plex-Platform-Version: 1.0' \
        -H 'X-Plex-Device-Name: PlexMediaServer' \
        -H 'X-Plex-Device: Linux' \
        "https://plex.tv/api/claim/exchange?token=${PLEX_CLAIM}" )"
  token="$( echo "$loginInfo" | sed -n 's/.*<authentication-token>\(.*\)<\/authentication-token>.*/\1/p' )"
  
  if [ "$token" ]; then
    setPref "PlexOnlineToken" "${token}"
    echo -e "\n\nPlex Media Server successfully claimed"
    systemctl restart plexmediaserver
  else
    echo -e "\n\nError claiming Plex Media Server"
    main_rc=1
  fi
else
    echo -e "\n\nPlex Media Server is already claimed"
fi

exit "${main_rc}"
