#!/bin/bash

#####
#
# This Script will update Plex Media Server to the latest version for Debian/Ubuntu
#
# To automatically check & update plex, run "crontab -e" and add the following lines
#
# # Check for Plex Media Server Updates every day @6:00 am
# 0 6 * * * /root/update-plexmediaserver.sh
#
#  2018 - Original by Matthieu Guerry
#       - Customised by erreur32
###

# Check Current installed version and exit if latest is already installed
service=plex
VersionInstalled=$(dpkg -s plexmediaserver | grep -Po '(?<=Version\: )(\S+)')
VersionAvailable=$(curl -s "https://plex.tv/downloads/details/1?build=linux-ubuntu-x86_64&channel=16&distro=ubuntu" | grep -Po '(?<=(\" version=\"))(\S+)(?=(\"))')
echo -e " Checking Plex version ... "
echo -e " Version installed = $VersionInstalled"
echo -e " Version Available = $VersionAvailable"

if [[ -z $VersionInstalled ]]; then echo " Plex is not installed - exit "; exit; fi
if [ $VersionAvailable = $VersionInstalled ]; then echo "Plex Media Server is already up-to-date (version $VersionInstalled) ... Bye! "; exit; fi

echo -e " Download new Version  $VersionAvailable"
# Download latest installation package to /tmp folder
curl -s "https://plex.tv/downloads/details/1?build=linux-ubuntu-x86_64&channel=16&distro=ubuntu" | grep -Po '(?<=url=\")(\S+)(?=\")' | xargs wget -P /tmp/

if [[ -z $(ps -ef |grep ${service}) ]]
then
   print "Hum service down !?! , anyway Service will updating\n"
else
   print "Plex is running, service will stop before Update...\n"
fi
# Stop Plex Service
sudo service plexmediaserver stop
# Install latest version
sudo dpkg -i /tmp/$(curl -s "https://plex.tv/downloads/details/1?build=linux-ubuntu-x86_64&channel=16&distro=ubuntu" | grep -Po '(?<=fileName=\")(\S+)(?=\")')


ps -ef | grep plex | grep -v grep
[ $?  -eq "0" ] && echo "Plex is running back :)" || echo "Plex is not running ... ;("

# Start Plex Service
echo -e " restart service Plex"
sudo service plexmediaserver start

# Remove installation package from /tmp folder
rm /tmp/plexmediaserver_*
