#!/bin/sh
#
# Message text handler function
# Simple function to keep code clean and pass mneumonic code and arguments to message-text script
MessageText(){
  "/var/packages/$SYNOPKG_PKGNAME/scripts/message-text" "$1" "$2" "$3" "$4"
}

# DSM 7 migration utility
# Migrate Plex Media Server from `Plex` share to new directory structure
Existing=0
[ "$SYNOPKG_PKGNAME" = "" ] && SYNOPKG_PKGNAME="PlexMediaServer"
[ "$SYNOPKG_PKGHOME" = "" ] && SYNOPKG_PKGHOME="/var/packages/$SYNOPKG_PKGNAME/home"
[ "$SYNOPKG_TEMP_LOGFILE" = "" ] && SYNOPKG_TEMP_LOGFILE=/tmp/PlexDebug.log

# Where is the shared folder?
PlexPkgShare="/var/packages/PlexMediaServer/shares/PlexMediaServer"
PlexPkgHome="$PlexPkgShare/AppData"
PlexPkgPath="$(readlink $PlexPkgHome)"

# Arguments
ExistingShare="$1"
ExistingPath="$ExistingShare/Library/Application Support/Plex Media Server"

# Step 1 - Not already migrated ?
if [ ! -e "$PlexPkgHome/Plex Media Server" ] || [ "$(ls "$PlexPkgHome/Plex Media Server")" = "" ]; then

  # Step 2 - Begin Migration process if existing existing DSM 6 server instance
  if [ "$(ls "$ExistingPath")" != "" ]; then

    # Start user error log (in case it's needed)
    MessageText "M-Migration-Started"

    # Capture all migration related output
    MigrationLog="$ExistingShare/Migration.log"
    echo "Plex Media Server migration to DSM 7 started:  $(date)" > $MigrationLog

    # Step 3a. Change ownership (optimized)
    echo "=== $(date) === Start: Change ownership" >> $MigrationLog
    chown "$SYNOPKG_PKGNAME":"$SYNOPKG_PKGNAME" "$ExistingShare" "$ExistingShare/Library" \
                                                "$ExistingShare/Library/Application Support" "$ExistingPath"
    for i in "$ExistingPath"/*
    do
      chown -RH "$SYNOPKG_PKGNAME":"$SYNOPKG_PKGNAME" "$i" >> $MigrationLog 2>&1 &
    done
    wait
    echo "=== $(date) === Completed: Change ownership" >> $MigrationLog

    # Stop if errors
    if [ $(grep "Operation not permitted" $MigrationLog) ]; then
      MessageText "M-Error-Changing-Ownership" "$MigrationLog"
      {
        echo "<br>$(date)\n<b>Errors encountered changing ownership.<br>"
        echo "Error log: $MigrationLog<br>"
        echo "Please consult our forums for assistance."
      } >>$SYNOPKG_TEMP_LOGFILE
      exit 150
    fi

    # Step 3b. Convert any absolute links (from backup/restores or old Subtitles agent) back to relative
    echo "=== $(date) === Start: Convert symbolic links" >>$MigrationLog
    find "$ExistingPath/Metadata" -type l | while read LinkFile
    do
      Location="$(realpath "$LinkFile")"
      ln -fs "$(realpath --relative-to="$(dirname "$(realpath -s "$LinkFile")")" "$Location")" "$LinkFile" >> $MigrationLog 2>&1
    done
    echo "=== $(date) === Completed:  Convert symbolic links" >>$MigrationLog

    # Stop if errors
    if [ $(grep "Operation not permitted" $MigrationLog) ]; then
      MessageText  "M-Error-Updating-Subtitles" "$MigrationLog"
      exit 150
    fi

    # Step 4 - Whack EAE.
    rm -rf "$ExistingPath"/Codecs/*/EasyAcessEncoder >/dev/null 2>&1

    # Step 5 - Migrate
    echo "=== $(date) === Start: Migrate Plex Media Server" >>$MigrationLog
    mv "$ExistingPath" "$PlexPkgHome"
    if [ $? -ne 0 ]; then
      MessageText "M-Migration-System-Error" "$ExistingPath" "$?" "$MigrationLog"
      exit 150
    fi

    MessageText "M-Migration-Successful" "$ExistingShare"
    echo "=== $(date) === Completed:  Migrate Plex Media Server" >>$MigrationLog

    # Step 6 - Clean up old directory location
    echo "=== $(date) === Start: Clean $ExistingShare" >>$MigrationLog
    rm -f "$ExistingShare/Please do not place any media files here."
    rm -f "$ExistingShare/Bitte legen Sie hier keine Mediendateien ab."
    rm -f "$ExistingShare/Veuillez ne placer aucun fichier multimédia ici."
    rm -f "$ExistingShare/Por favor, no coloque ningún archivo multimedia aquí."
    rm -f "$ExistingShare/ここにメディアファイルを置かないでください。"
    rm -f "$ExistingShare/请不要在此处放置任何媒体文件。"

    # Remove old DSM Indexes and .DS_Store files if present
    rm -f  "$ExistingShare/Library/Application Support/.DS_Store" >/dev/null 2>&1
    rm -rf "$ExistingShare/Library/Application Support/@eaDir"    >/dev/null 2>&1
    rm -f  "$ExistingShare/Library/.DS_Store"                     >/dev/null 2>&1
    rm -rf "$ExistingShare/Library/@eaDir"                        >/dev/null 2>&1

    # Remove old Plex directories
    rmdir  "$ExistingShare/Library/Application Support"           >/dev/null 2>&1
    rmdir  "$ExistingShare/Library"                               >/dev/null 2>&1
    rm -rf "$ExistingShare/tmp_transcoding"                       >/dev/null 2>&1

    echo "=== $(date) === Completed: Clean $ExistingShare" >>$MigrationLog
    MessageText "M-Migration-Cleaned" "$ExistingShare"
  fi
fi

# Step 7 - Remove all previous log files if present as they are obsolete
rm -rf "$PlexPkgHome/Plex Media Server/Logs"/* >/dev/null 2>&1
exit 0
