#!/bin/bash

mkdir -p /etc/root 2> /dev/null
rootperm=$?
if [ $rootperm -eq 0 ] ; then
  rm -rf /etc/root
else
  echo "Root permission is required to run this script"
  exit
fi

if [ ! -f /usr/bin/apt ] ; then
  echo "This script is only for Debian-based systems"
  exit
fi

echo "Checking plex-media-server version"
version_plex=$(curl "https://plex.tv/pms/downloads/5.json" 2> /dev/null | python3 -m json.tool | grep "amd64.deb" | grep "debian" | tr -s " "  | cut -d ":" -f 3 | cut -d "," -f 1 | cut -d '"' -f 1)
version_plex="https:${version_plex}"
version_plex_current=$(cat /etc/plex_version.conf)
if [ "${version_plex}" != "${version_plex_current}" ] ; then
  echo "New plex-media-server version detected"
  echo "Downloading plex-media-server"
  rm -rf /tmp/plex.deb
  wget -q --show-progress -c "${version_plex}" -O /tmp/plex.deb
  echo "Installing plex-media-server"
  apt install /tmp/plex.deb
  error_install=$?
  if [ ${error_install} -eq 0 ] ; then
    echo "${version_plex}" > /etc/plex_version.conf
  fi
else
  echo "No updates for plex-media-server"
fi
