#!/bin/sh

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

# create user with random password
  synouser --add plex $(uuidgen) 'Plex User' 0 '' '' 2> /dev/null 1> /dev/null
else
  synouser --setpw plex $(uuidgen) 2> /dev/null 1> /dev/null
  synouser --modify plex 'Plex User' 0 '' 2> /dev/null 1> /dev/null
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> /dev/null 1> /dev/null
if [ $? -eq 0 ]; then

  # 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" 2> /dev/null 1> /dev/null

else
  # Check for interfering files on selected volume

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

    # 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
    rm -rf $SYNOPKG_PKGDEST_VOL/Plex.old

    # Rename this one to be '.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
  synoshare --add Plex "Plex metadata storage" $PLEX_LIBRARY_PATH "" "plex,admin" "" 1 7 2> /dev/null 1> /dev/null
  synoshare --setuser Plex RW = plex,admin  2> /dev/null 1> /dev/null

fi

# Set rights on Plex share
synoshare --setuser Plex RW = plex,admin  2> /dev/null 1> /dev/null

# 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." 2> /dev/null 1> /dev/null
touch "$PLEX_LIBRARY_PATH/Bitte legen Sie hier keine Mediendateien ab." 2> /dev/null 1> /dev/null
touch "$PLEX_LIBRARY_PATH/Veuillez ne placer aucun fichier multimédia ici." 2> /dev/null 1> /dev/null
touch "$PLEX_LIBRARY_PATH/Por favor, no coloque ningún archivo multimedia aquí." 2> /dev/null 1> /dev/null
touch "$PLEX_LIBRARY_PATH/ここにメディアファイルを置かないでください。" 2> /dev/null 1> /dev/null
touch "$PLEX_LIBRARY_PATH/请不要在此处放置任何媒体文件。" 2> /dev/null 1> /dev/null

# Set the ACLs to standard
synoacltool -del $PLEX_LIBRARY_PATH                                                2> /dev/null 1> /dev/null
synoacltool -add $PLEX_LIBRARY_PATH group:administrators:allow:rwxpdDaARWc--:fd--  2> /dev/null 1> /dev/null
synoacltool -add $PLEX_LIBRARY_PATH user:admin:allow:rwxpdDaARWc:fd--              2> /dev/null 1> /dev/null
synoacltool -add $PLEX_LIBRARY_PATH user:plex:allow:rwxpdDaARWcCo:fd--             2> /dev/null 1> /dev/null

# Verify the Plex share is visible from File Station for those with access permission
synoshare --setbrowse Plex 1 2> /dev/null 1> /dev/null

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

if [ ! -d  "$PLEX_LIBRARY_PATH/Library/Application Support/Plex Media Server" ]; then
  mkdir -p "$PLEX_LIBRARY_PATH/Library/Application Support/Plex Media Server" 2> /dev/null 1> /dev/null
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 2> /dev/null 1> /dev/null
  chown plex:users "$PLEX_LIBRARY_PATH/Library/Application Support/Plex Media Server/Preferences.xml" 2> /dev/null 1> /dev/null
  chown -R plex:users "$PLEX_LIBRARY_PATH/Library/Application Support/Plex Media Server/Plug-in Support" 2> /dev/null 1> /dev/null

  # Now launch the blanket fix-everything
  chown -R plex:users $PLEX_LIBRARY_PATH/Library 2> /dev/null 1> /dev/null &

  # 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 2> /dev/null
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 2> /dev/null
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 2> /dev/null 1> /dev/null
if [ $? -ne 0 ]; then
  synogroup --add video plex 2> /dev/null 1> /dev/null
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 2> /dev/null 1> /dev/null
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  2> /dev/null 1> /dev/null

# Now save the Plex share's location
if [ -d "/var/packages/Plex Media Server/target" ]; then
  echo "$PLEX_LIBRARY_PATH/Library/Application Support" > "/var/packages/Plex Media Server/target/plex_library_path"
fi

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

exit 0
