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


# Possible installation states:
# 1. Re-installation with previous DSM 7-based installation
# 2. Installation with possible DSM 7-based installation in stasis.
# 3. Installation with possible DSM 6-based "Plex" share to migrate
# 4. Installation with possible DSM 6-based "plex" share to migrate
# 5. New install


# 1. Installation with previous DSM-7 installation somewhere in statis?  (install that volume if found)
for i in /volume[1-9]*
do
  if [    -d "$i/@apphome/$SYNOPKG_PKGNAME/Plex Media Server" ] && \
     [ "$(ls "$i/@apphome/$SYNOPKG_PKGNAME/Plex Media Server")" != "" ] && \
     [ "$SYNOPKG_PKGDEST_VOL" != "$i" ]; then

    ExistingVolume="$(echo $i | sed -e 's;/volume;Volume ;')"
    TargetVolume="$(echo $SYNOPKG_PKGDEST_VOL | sed -e 's;/volume;Volume ;')"

    # Instructions for user
    MessageText M-Preinstall-Wrong-Volume "$ExistingVolume" "$TargetVolume"

    exit 1
  fi
done


# 2. Look for existing Plex share somewhere to migrate  (exclude "Plex" shared folders on removable media)
SourceShare=""

# Find it if out there.  First found wins
[ "$(echo /volume[1-9]*/[Pp]lex/Library/Application\ Support/Plex\ Media\ Server)" != "/volume[1-9]*/[Pp]lex/Library/Application Support/Plex Media Server" ] && \
   SourceShare="$(echo /volume[1-9]*/[Pp]lex | awk '{print $1}')"


# 3. Is there a valid installation out there?
if [ "$SourceShare" != "" ]; then

  # Might be something - check further
  # Installation with previous DSM 4/5/6-created "Plex" (or "plex") share to migrate.  Install on that volume
  ExistingVolume=""
  for i in /volume[1-9]*
  do
    # Check Volume (globs are nice)
    if [    -d $i/[Pp]lex/Library/Application\ Support/Plex\ Media\ Server ] && \
       [ "$(ls $i/[Pp]lex/Library/Application\ Support/Plex\ Media\ Server)" != "" ] && \
       [ "$SYNOPKG_PKGDEST_VOL" != "$i" ]; then

      ExistingVolume="$(echo $i | sed -e 's;/volume;Volume ;')"

      # Instructions for user
      MessageText M-Preinstall-Migrate-Wrong-Volume "$ExistingVolume"
      exit 150
    fi
  done

  # 4. Volume OK - Check ACLs if we're not reinstalling DSM 7
  Exempt=0

  # Check for reasons not to preinstall check ACLs
  [ -d /volume*/PlexMediaServer/AppData/Plex\ Media\ Server ] && Exempt=1
  [ -d /volume*/@apphome/PlexMediaServer/Plex\ Media\ Server ] && Exempt=1

  Candidate="$(echo /volume*/@apphome/PlexMediaServer/Plex\ Media\ Server)"

  if [ $Exempt -eq 0 ] && [ "$(synoacltool -get $SourceShare | grep "user:PlexMediaServer:allow:rwxpdDaARWcCo:fd--")" = "" ]; then

    MessageText M-Preinstall-Check-Failure
    MessageText M-ACL-Procedure
    exit 150
  fi
fi

# 5. No news is good news
rm -f "$SYNOPKG_TEMP_LOGFILE"
exit 0
