#!/bin/sh

# Path to this script
ScriptDir="$(dirname "$0")"

# Set Prefs
SetPref()
{
  local PrefXml="$SYNOPKG_PKGHOME/Plex Media Server/Preferences.xml"

  sed -i "s;/>; $1=\""$2"\" />;" "$PrefXml"
}

# Message text handler function
# Simple function to keep code clean and pass mneumonic code and arguments to message-text script
MessageText(){
  "$ScriptDir/message-text" "$1" "$2" "$3" "$4"
}

# If there is no DSM 7 installation existing
if [ ! -e "$SYNOPKG_PKGHOME/Plex Media Server" ] || [ "$(ls "$SYNOPKG_PKGHOME/Plex Media Server")" = "" ]; then

  # And there appears to be a DSM 6-based Plex installation
  if [ "$(echo /volume*/Plex/Library)" != "/volume*/Plex/Library" ]; then

    # Test for Plex share access
    if [ "$(synoacltool -get "$SYNOPKG_PKGDEST_VOL/Plex" | grep "user:PlexMediaServer:allow:rwxpdDaARWcCo:fd--")" = "" ]; then
      MessageText M-ACL-Failure-Plex-Share
      MessageText M-ACL-Procedure
      exit 150
    fi

    # Verify contents are not still in Linux mode but are owned by admin
    if [ "$(synoacltool -get "$SYNOPKG_PKGDEST_VOL/Plex/Library"                                       | grep Linux)" != "" ] || \
       [ "$(synoacltool -get "$SYNOPKG_PKGDEST_VOL/Plex/Library/Application Support"                   | grep Linux)" != "" ] || \
       [ "$(synoacltool -get "$SYNOPKG_PKGDEST_VOL/Plex/Library/Application Support/Plex Media Server" | grep Linux)" != "" ]; then

      MessageText M-ACL-Failure-Plex-Subdirs
      MessageText M-ACL-Procedure
      exit 150
    fi

    # Final check to confirm we have ACL control of subdirectories before continuing.
    Errors=0

    find " $SYNOPKG_PKGDEST_VOL/Plex/Library/Application Support" -maxdepth 5 -type d | while read Dir
    do
      [ "$(synoacltool -get "$Dir" | grep "user:PlexMediaServer:allow:rwxpdDaARWcCo:fd--")" = "" ] && Errors=$((Errors + 1))
    done

    # If any errors,  do the above again.
    if [ $Errors -gt 0 ]; then

      MessageText M-Cannot-Migrate-ACL-Incomplete
      MessageText M-ACL-Procedure
      exit 150
    fi

    # Perform migration of existing Plex server data
    "$ScriptDir/dsm7-migration-tool"
    [ $? -ne 0 ] && exit $?
  fi
fi

# Redirect logfiles
if [ "$WUserDefined" = "true" ] ; then

  # If alternative PLEX_MEDIA_SERVER_LOG_DIR location specified,  test validity then save for later use.
  if [ -n "$WLogPathname" ]; then

    # Test if exists
    if [ ! -w "$WLogPathname" ]; then

      # Report error - Cannot write to given location
      MessageText M-LogPath-No-Write-Access "$WLogPathname"
      exit 1
    fi
  else

      # Report error - Forgot to give location
      MessageText M-LogPath-No-Path-Specified
      exit 1
  fi

  # Given location exists,  save the location for us to use
  echo -n "$WLogPathname" > "$SYNOPKG_PKGHOME/PlexMediaServerLogDir"

  # If any existing logs in the default location,  move them here.
  if [ -d "$SYNOPKG_PKGHOME/Plex Media Server/Logs" ] && \
     [ "$(ls "$SYNOPKG_PKGHOME/Plex Media Server/Logs/")" != "" ]; then

      # Move existing logs to new home to preserve them
      mv "$SYNOPKG_PKGHOME/Plex Media Server"/Logs/*  "$WLogPathname"
  fi

# Cancel log file redirection
elif [ "$WStoreInternal" = "true" ]; then

  # Remove it
  rm -f "$SYNOPKG_PKGHOME/PlexMediaServerLogDir"
fi

# Remind user to check permissions
MessageText M-Install-Complete-Check-Permissions

# Process claim token if supplied
if [ "$WUseClaimToken" = "true" ]; then

  # Token supplied
  if [ "$WClaimToken" = "" ]; then

    # Token login selected but no token provided
    MessageText M-Claim-No-Token-Provided
    exit 1
  fi

  # Remove the current identity if exists
  if [ -e "$SYNOPKG_PKGHOME/Plex Media Server/Preferences.xml" ]; then

    # Get existing ClientID (ProcessedMachineID) for use below
    ClientId="$(cat "$SYNOPKG_PKGHOME/Plex Media Server/Preferences.xml"| \
                tail -1                                                 | \
                sed -e 's/.*ProcessedMachineIdentifier="//'             | \
                sed -e 's/".*//'                                        )"

    # Edit existing preferences so PMS sees us as signed out.
    sed -i 's/PlexOnlineToken="[^"]*"//'    "$SYNOPKG_PKGHOME/Plex Media Server/Preferences.xml"
    sed -i 's/PlexOnlineUsername="[^"]*"//' "$SYNOPKG_PKGHOME/Plex Media Server/Preferences.xml"
    sed -i 's/PlexOnlineMail="[^"]*"//'     "$SYNOPKG_PKGHOME/Plex Media Server/Preferences.xml"
    sed -i 's/PlexOnlineHome="[^"]*"//'     "$SYNOPKG_PKGHOME/Plex Media Server/Preferences.xml"
  else

    # Fresh installation, Create Preferences.xml
    echo '<?xml version="1.0" encoding="utf-8"?>' > "$SYNOPKG_PKGHOME/Plex Media Server/Preferences.xml"
    echo '<Preferences/>'                        >> "$SYNOPKG_PKGHOME/Plex Media Server/Preferences.xml"

    # Set MachineID
    # Setup Server's client identifier
    SerialNum="$(uuidgen)"
    SetPref "MachineIdentifier" "$SerialNum"

    ClientId="$(echo -n "${SerialNum}- Plex Media Server" | sha1sum | cut -b 1-40)"
    SetPref "ProcessedMachineIdentifier" "${ClientId}"
  fi

  # Get model for Device field
  Device="$(get_key_value /etc.defaults/synoinfo.conf unique|cut -d'_' -f3|sed 's/^ds/DS/;s/^fs/FS/;s/^rs/RS/'|sed 's/^\([0-9]\)/DS\1/')"

  # DSM version info
  DSMversion="$(get_key_value /etc.defaults/VERSION productversion)"
  DSMbuild="$(get_key_value /etc.defaults/VERSION buildnumber)"
  DSMupdate="$(get_key_value /etc.defaults/VERSION smallfixnumber)"

  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: DSM $DSMversion.$DSMbuild-$DSMupdate" \
                    -H "X-Plex-Device-Name: PlexMediaServer" \
                    -H "X-Plex-Device: ${Device}" \
                    "https://plex.tv/api/claim/exchange?token=${WClaimToken}")"

  # If errors, redo claim sequence
  if [ $? -ne 0 ]; then

    MessageText M-Could-Not-Claim
    exit 1
  fi

  # Extract values
  Username="$(echo "$LoginInfo" | sed -n 's/.*<username>\(.*\)<\/username>.*/\1/p')"
  Email="$(echo "$LoginInfo" | sed -n 's/.*<email>\(.*\)<\/email>.*/\1/p')"
  Token="$(echo "$LoginInfo" | sed -n 's/.*<authentication-token>\(.*\)<\/authentication-token>.*/\1/p')"

  # Write info to Preferences and continue to start
  SetPref PlexOnlineUsername "$Username"
  SetPref PlexOnlineMail "$Email"
  SetPref PlexOnlineToken "$Token"

  # Inform user
  MessageText M-Claim-Successful "$Username"
fi
exit 0
