#!/bin/sh

# DSM version variables
DSM_VERSION="$(get_key_value /etc.defaults/VERSION productversion)"
DSM_BUILD="$(get_key_value /etc.defaults/VERSION buildnumber)"
DSM_UPDATE="$(get_key_value /etc.defaults/VERSION smallfixnumber)"

# Set identification variables
PMS_INFO_VENDOR=Synology
PMS_INFO_DEVICE="$(get_key_value /etc.defaults/synoinfo.conf unique|cut -d'_' -f3|sed 's/^ds/DS/;s/^fs/FS/;s/^rs/RS/'|sed 's/^\([0-9]\)/DS\1/')"
PMS_INFO_MODEL="$(uname -m)"
PMS_INFO_PLATFORM_VERSION="DSM $DSM_VERSION.$DSM_BUILD-$DSM_UPDATE"

# Base Plex installation directory
PLEX_DIR="/var/packages/Plex Media Server/target"

# Find the Plex share
PLEX_PATH="$(/usr/syno/sbin/synoshare --get Plex | grep Path | awk -F[ '{print $2}' | awk -F] '{print $1}')"
if [ "$PLEX_PATH" = "" ]; then

  # Issue error to users (Not Found - rerun installation)
  echo "The Plex share could not be found.  Please check your configuration, reinstall Plex, or ask in our Support Forums." > $SYNOPKG_TEMP_LOGFILE
  exit 150
fi

# Set final variables
PLEX_LIBRARY_PATH="$PLEX_PATH/Library/Application Support"
PID_FILE="$PLEX_LIBRARY_PATH/Plex Media Server/plexmediaserver.pid"

# Verify tmp_transcoding directory exists.  Silently recreate if possible.
if [ ! -d "${PLEX_PATH}/tmp_transcoding" ]; then

  # There is nothing there or not a directory,  Silently recreate if possible
  rm -rf "${PLEX_PATH}/tmp_transcoding"
  mkdir -p "${PLEX_PATH}/tmp_transcoding"
  if [ $? -ne 0 ]; then

    echo "The Plex 'tmp_transcoding' directory was missing.  Attempts to recreate it failed.  Please repair manually or ask in our Support Forums." > $SYNOPKG_TEMP_LOGFILE
    exit 150
  fi

  # Grant permissions
  chown plex:users ${PLEX_PATH}/tmp_transcoding
fi

# Plex status must now be defined before parsing below
plex_status()
{
    if [ ! -f "$PID_FILE" ]
    then
        return 1
    fi
    if [ -d /proc/`cat "$PID_FILE"` ]
    then
        return 0
    else
        return 1
    fi
}

start_plex ()
{
    # Verify device permissions are intact
    Changed=0

    # Ensure the TV Butler udev rule exists
    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
      Changed=1
    fi

    # Check if this model supports HW transcoding
    if [ -d /dev/dri ]; then

      # Ensure the HW Transcoding udev rule exists
      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
        Changed=1

      # If the HW Transcoding udev rule exists, ensure it is correct
      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
        Changed=1
      fi

      # Check if permissions correct
      if [ "$(ls -la /dev/dri/renderD128 | awk -F' ' '{print $4}')" != "video" ]; then
        Changed=1
      fi
    fi

    # Retrigger udevadm if needed
    if [ $Changed -eq 1 ]; then
      sync
      udevadm trigger
      sleep 3
    fi

    # Continue with normal PMS start
    PLEX_PATH=$(/usr/syno/sbin/synoshare --get Plex | grep Path | awk -F[ '{print $2}' | awk -F] '{print $1}')
    su plex -s /bin/sh -c \
    "export LC_ALL=en_US.utf8; \
     export LANG=en_US.utf8; \
     export LD_LIBRARY_PATH='$PLEX_DIR/lib'; \
     export PLEX_MEDIA_SERVER_MAX_PLUGIN_PROCS=6; \
     export PLEX_MEDIA_SERVER_APPLICATION_SUPPORT_DIR='$PLEX_LIBRARY_PATH'; \
     export TMPDIR=$PLEX_PATH/tmp_transcoding; \
     export PLEX_MEDIA_SERVER_DEFAULT_PREFERENCES='HardwareAcceleratedCodecs=true&TranscoderCanOnlyRemuxVideo=false'; \
     export PLEX_MEDIA_SERVER_INFO_VENDOR='$PMS_INFO_VENDOR'; \
     export PLEX_MEDIA_SERVER_INFO_DEVICE='$PMS_INFO_DEVICE'; \
     export PLEX_MEDIA_SERVER_INFO_MODEL='$PMS_INFO_MODEL'; \
     export PLEX_MEDIA_SERVER_INFO_PLATFORM_VERSION='$PMS_INFO_PLATFORM_VERSION'; \
     export PLEX_BROWSER_NO_HOME_DIR=1; \
     ulimit -s 3000; \
     sleep 2; \
     /var/packages/Plex\ Media\ Server/target/Plex\ Media\ Server >/dev/null 2>&1 &"

    counter=20
    while [ $counter -gt 0 ]
    do
        plex_status && break
        let counter=counter-1
        sleep 1
    done

    # Give 3 seconds to get started
    sleep 3

    # create DSM shortcut
    if [ ! -f "/usr/syno/synoman/webman/3rdparty/plex" ]
    then
        ln -s "$PLEX_DIR/dsm_config/plex" /usr/syno/synoman/webman/3rdparty
    fi
    plex_status

}

stop_plex ()
{

    # Make first requests nicely
    Count=11

    # Ask nicely for 1 minute
    while [ "$(ps -ef | grep -i ^plex | grep "Plex Media Server"| wc -l)" -ne 0 ] &&  [ $Count -gt 0 ]
    do

      if [ -f "$PID_FILE" ]; then

        kill -15 $(cat "$PID_FILE")
        sleep 5
      fi

      Count=$(($Count - 1))

    done

    # PMS has been asked nicely to shut down for 1 minute but has not.
    # Now we take down any processes owned by user 'plex'
    Pids="$(ps -ef | grep -i ^plex | awk '{print $2}')"

    Count=10
    Sig=-9

    while [ "$Pids" != "" ] && [ $Count -gt 0 ]
    do
        # Kill what's still running
        kill $Sig $Pids
        sleep 5

        # Look again
        Pids="$(ps -ef | grep -i ^plex | awk '{print $2}')"
        Count=$(($Count -1))

        # Force them down if our last iteration
        if [ $Count -eq 1 ]; then
          Sig=-11
        fi
    done

    # Remove the Package Manager linkage
    rm -rf /usr/syno/synoman/webman/3rdparty/plex
}

case $1 in
    start)
        echo Starting Plex ...
        start_plex
        exit $?
        ;;
    stop)
        echo Stopping Plex ...
        stop_plex
        exit $?
        ;;
    status)
        if plex_status
        then
            echo Plex is running
            exit 0
        else
            echo Plex is not running
            exit 1
        fi
        ;;
    log)
        echo "$PLEX_LIBRARY_PATH/Plex Media Server/Logs/Plex Media Server.log"
        exit 0
        ;;
    *)
        exit 1
        ;;
esac
