#!/bin/sh

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

# 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"
}

# 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

exit 0
