#!/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 | cut -c-8` 'Plex User' 0 '' ''
else
    echo Securing existing Plex user
    synouser --modify plex 'Plex User' 0 ''
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

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 Media Library" $PLEX_LIBRARY_PATH "" "admin,plex" "" 1 7
  synoshare --setuser Plex RW = admin,plex

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

# Check and add ACLs if required
if [ "`synoacltool -get $PLEX_LIBRARY_PATH | grep \"user:plex\"`" ]; then

  synoacltool -replace $PLEX_LIBRARY_PATH \
    `synoacltool -get $PLEX_LIBRARY_PATH|grep "user:plex" | awk 'BEGIN { OFS=" "; } { gsub(/[^[:alnum:]]/, "", $1); print $1;}'|head -1` \
    user:plex:allow:rwxpdDaARWcCo:fd--

else

  synoacltool -add $PLEX_LIBRARY_PATH user:plex:allow:rwxpdDaARWcCo:fd--

fi

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

# Verify the plex user is in administrators group (Syno share perm fix)
if [ `grep administrators /etc/group|grep plex|wc -l` -eq 0 ]
then
  sed -i '/administrators:/s/$/,plex/' /etc/group
fi


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

# If user 'plex' is not the current owner of Library,  make it so
if [ -d $PLEX_LIBRARY_PATH/Library ] && \
   [ "`ls -al $PLEX_LIBRARY_PATH/|grep "Library"|awk '{print $3}'`" != "plex" ]
then
    chown -R plex:users $PLEX_LIBRARY_PATH/* &
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="0660"' > /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"


exit 0
