#!/bin/sh


#### DEBUG
#export SYNOPKG_DSM_LANGUAGE=ger


# 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. New install

Error=0

# 1. Reinstallation with previous DSM 7-based PMS in statis
if [    -d "$SYNOPKG_PKGDEST_VOL/@apphome/$SYNOPKG_PKGNAME/Plex Media Server" ] && \
   [ "$(ls "$SYNOPKG_PKGDEST_VOL/@apphome/$SYNOPKG_PKGNAME/Plex Media Server")" != "" ]; then

  # ok
  exit 0
fi

# 2. Installation with previous DSM-7 installation somewhere in statis?
for i in /volume*
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

# Exit if error and show user
[ $Error -gt 0 ] && exit $Error

# 3. Look for existing Plex share somewhere to migrate  (exclude "Plex" shared folders on removable media)
if [ "$(echo /volume[1-9]*/Plex)" != "/volume[1-9]*/Plex" ]; then

  # Might be something - check further
  # Installation with previous DSM 6-based "Plex" share to migrate
  for i in /volume*
  do
    # Check Volume
    if [    -d "$i/Plex/Library/Application Support" ] && \
       [ "$(ls "$i/Plex/Library/Application Support")" != "" ] && \
       [ "$(grep USB "$i")" == "" ] && [ "$(grep SATA "$i")" == "" ] && \
       [ "$SYNOPKG_PKGDEST_VOL" != "$i" ]; then

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

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

      exit 1
    fi
  done

  # 4. Volume OK - Check ACLs
  if [ "$(synoacltool -get $SYNOPKG_PKGDEST_VOL/Plex | grep "user:PlexMediaServer:allow:rwxpdDaARWcCo:fd--")" = "" ]; then

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

# Exit if error and show user
[ $Error -gt 0 ] && exit $Error

# 5. Default condition: New Installation  (No existing installation anywhere)
rm -f "$SYNOPKG_TEMP_LOGFILE"
exit 0
