#!/bin/sh

# Ensure user 'plex' exists before doing anything
synouser --get plex 2>&1 > /dev/null
if [ $? -ne 0 ]; then

# create user with random password
  echo "Creating Plex user."
  synouser --add plex $(uuidgen) 'Plex User' 0 '' ''
else
  echo "Securing existing Plex user"
  synouser --setpw plex $(uuidgen)
  synouser --modify plex 'Plex User' 0 ''
fi

# Remove from administrators group if present
if [ "$(grep 'administrators:.*plex' /etc/group)" != "" ]; then
  sed -i '/administrators:/s/,plex//' /etc/group
fi

# Determine status of Plex share
synoshare --get Plex 2>&1 > /dev/null
if [ $? -eq 0 ]; then
  echo "Found existing Plex share"

  # find out where it is and save its location
  PLEX_LIBRARY_PATH="$(synoshare --get Plex | grep Path | awk -F\[ '{print $2}' | awk -F\] '{print $1}')"

  # Export library location to the rest of script & environment
  export PLEX_LIBRARY_PATH

  # Make certain the share description is updated
  synoshare --setdesc Plex "Plex metadata storage"

else
  # Check for interfering files on selected volume
  echo "Checking for existing files or directories which interfere with installation"

  # Does a file exist?  If so, delete it.  It will stop Plex from installing
  if [ -f $SYNOPKG_PKGDEST_VOL/Plex ]; then
    echo "Found stray file.  Deleting"
    rm -f $SYNOPKG_PKGDEST_VOL/Plex
  fi

  # Does a stray directory exist?  If so, rename it and let the user resolve.
  if [ -d $SYNOPKG_PKGDEST_VOL/Plex ]; then

    # Delete existing Plex.old if it exists
    echo "Deleting Plex.old if it exists"
    rm -rf $SYNOPKG_PKGDEST_VOL/Plex.old

    # Rename this one to be '.old'
    echo Renaming stray Plex directory to "Plex.old"
    mv $SYNOPKG_PKGDEST_VOL/Plex  $SYNOPKG_PKGDEST_VOL/Plex.old
  fi

  # Establish PLEX_LIBRARY_PATH
  export PLEX_LIBRARY_PATH="$SYNOPKG_PKGDEST_VOL/Plex"


  # Create share and add basic permissions here
  echo "Creating Plex share."
  synoshare --add Plex "Plex metadata storage" $PLEX_LIBRARY_PATH "" "plex,admin" "" 1 7
  synoshare --setuser Plex RW = plex,admin

fi

# Log file output where it's located
echo "Plex share located at $PLEX_LIBRARY_PATH"


# Set rights on Plex share
synoshare --setuser Plex RW = plex,admin

# Add friendly warnings not to place media files in the Plex share in multiple languages
# English, German, French, Spanish, Japanese, Chinese (simplified)
touch "$PLEX_LIBRARY_PATH/Please do not place any media files here."
touch "$PLEX_LIBRARY_PATH/Bitte legen Sie hier keine Mediendateien ab."
touch "$PLEX_LIBRARY_PATH/Veuillez ne placer aucun fichier multimédia ici."
touch "$PLEX_LIBRARY_PATH/Por favor, no coloque ningún archivo multimedia aquí."
touch "$PLEX_LIBRARY_PATH/ここにメディアファイルを置かないでください。"
touch "$PLEX_LIBRARY_PATH/请不要在此处放置任何媒体文件。"

# Set the ACLs to standard
synoacltool -del $PLEX_LIBRARY_PATH
synoacltool -add $PLEX_LIBRARY_PATH group:administrators:allow:rwxpdDaARWc--:fd--
synoacltool -add $PLEX_LIBRARY_PATH user:admin:allow:rwxpdDaARWc:fd--
synoacltool -add $PLEX_LIBRARY_PATH user:plex:allow:rwxpdDaARWcCo:fd--

# Verify the Plex share is visible from File Station for those with access permission
synoshare --setbrowse Plex 1

# Create temp transcoding and "Plex Media Server" directories if required
if [ ! -d $PLEX_LIBRARY_PATH/tmp_transcoding ]; then
  mkdir   $PLEX_LIBRARY_PATH/tmp_transcoding
fi

if [ ! -d  "$PLEX_LIBRARY_PATH/Library/Application Support/Plex Media Server" ]; then
  mkdir -p "$PLEX_LIBRARY_PATH/Library/Application Support/Plex Media Server"
fi

# Are Ownership corrections needed?  ( We will do this normally when first creating the share. )
FixOwner=0;

# If plex:users is not the current owner of Library,  make it so
[ -d $PLEX_LIBRARY_PATH/Library ]         && [ "$(stat -c %U $PLEX_LIBRARY_PATH/Library)" != "plex"  ] && FixOwner=1
[ -d $PLEX_LIBRARY_PATH/Library ]         && [ "$(stat -c %G $PLEX_LIBRARY_PATH/Library)" != "users" ] && FixOwner=1

[ -d $PLEX_LIBRARY_PATH/tmp_transcoding ] && [ "$(stat -c %U $PLEX_LIBRARY_PATH/tmp_transcoding)" != "plex"  ] && FixOwner=1
[ -d $PLEX_LIBRARY_PATH/tmp_transcoding ] && [ "$(stat -c %G $PLEX_LIBRARY_PATH/tmp_transcoding)" != "users" ] && FixOwner=1

# Do we need set owner & group?
if [ $FixOwner -eq 1 ]; then

  # Fix tmp_transcoding, Preferences.xml and Plug-in Support first
  chown -R plex:users $PLEX_LIBRARY_PATH/tmp_transcoding
  chown plex:users "$PLEX_LIBRARY_PATH/Library/Application Support/Plex Media Server/Preferences.xml"
  chown -R plex:users "$PLEX_LIBRARY_PATH/Library/Application Support/Plex Media Server/Plug-in Support"

  # Now launch the blanket fix-everything
  chown -R plex:users $PLEX_LIBRARY_PATH/Library &

  # Give the chown time to execute before starting. (minimize false errors for large libraries)
  sleep 3
fi


# To handle TV Butler cards and fix HW Transcoding we need to make a Video group and fix some devices.

# Setup udev rule for TV Butler device for that specific vendor ID.
if [ ! -f /lib/udev/rules.d/60-tv-butler-fix.rules ]; then
  echo 'SUBSYSTEM=="usb", ATTRS{idVendor}=="1d19", ATTRS{idProduct}=="0100", GROUP="video", MODE="0664"' > /lib/udev/rules.d/60-tv-butler-fix.rules
elif [ $(grep -c 0664 /lib/udev/rules.d/60-tv-butler-fix.rules) -eq 0 ]; then
  echo 'SUBSYSTEM=="usb", ATTRS{idVendor}=="1d19", ATTRS{idProduct}=="0100", GROUP="video", MODE="0664"' > /lib/udev/rules.d/60-tv-butler-fix.rules
fi

# If video group doesn't exist create it and ensure Plex is part of it. And add a udev rule for the drm group.
synogroup --get video
if [ $? -ne 0 ]; then
  synogroup --add video plex
elif [ $(synogroup --get video|grep -c "\[plex\]") -eq 0 ]; then
  synogroup --get video |grep -E '^[0-9]:|[0-9][0-9]:'|cut -d":" -f2|xargs echo|sed "s/\[/'/g;s/\]/'/g"|xargs synogroup --member video plex
fi
if [ ! -f /lib/udev/rules.d/60-fix-plex-hw-transcoding.rules ]; then
  echo 'SUBSYSTEM=="drm", GROUP="video"' > /lib/udev/rules.d/60-fix-plex-hw-transcoding.rules
elif [ "`grep -c drm /lib/udev/rules.d/60-fix-plex-hw-transcoding.rules`" -eq 0 ]; then
  echo 'SUBSYSTEM=="drm", GROUP="video"' > /lib/udev/rules.d/60-fix-plex-hw-transcoding.rules
fi

# Ensure we apply the udev rules from the written files.
sync
udevadm trigger

# Now save the Plex share's location
echo "Saving current Plex share location to 'plex_library_path'"

echo "$PLEX_LIBRARY_PATH/Library/Application Support" > "/var/packages/Plex Media Server/target/plex_library_path"

# Remove any old "/1" if existed
rm -f "/1"

exit 0
