#!/bin/bash

# Suggested filename: update-emby.sh

set -euo pipefail

# Configuration
OWNER="MediaBrowser"
REPO="Emby.Releases"
DOWNLOAD_DIR="/tmp"
DEB_ARCH="amd64"

# Ensure required commands are available
for cmd in curl grep sed dpkg systemctl pgrep; do
  if ! command -v "$cmd" >/dev/null 2>&1; then
    echo "Error: '$cmd' is required but not installed." >&2
    exit 1
  fi
done

# Get installed Emby version
installed_version=$(dpkg-query -W -f='${Version}' emby-server 2>/dev/null || echo "none")

# Get latest release version from GitHub
latest_version=$(curl -sIL "https://github.com/$OWNER/$REPO/releases/latest" \
  | grep -i "^location:" \
  | sed -E 's|.*tag/([^[:space:]/]+).*|\1|')

if [[ -z "$latest_version" ]]; then
  echo "Failed to fetch the latest version."
  exit 1
fi

echo "Installed version: $installed_version"
echo "Latest version:    $latest_version"

# Compare versions (skip if already up to date)
if [[ "$installed_version" == "$latest_version" ]]; then
  echo "Emby Server is already up to date."
  exit 0
fi

# Download the .deb package
deb_file="emby-server-deb_${latest_version}_${DEB_ARCH}.deb"
download_url="https://github.com/$OWNER/$REPO/releases/download/${latest_version}/${deb_file}"
download_path="${DOWNLOAD_DIR}/${deb_file}"

echo "Downloading Emby Server $latest_version..."
curl -L -o "$download_path" "$download_url"

# Stop Emby safely if running
if pgrep -x embyserver > /dev/null; then
  echo "Stopping Emby Server..."
  sudo systemctl stop emby-server.service
fi

# Install the update
echo "Installing Emby Server $latest_version..."
sudo dpkg -i "$download_path"

# Remove downloaded file after successful installation
echo "Cleaning up..."
rm -f "$download_path"

# Re-enable and start Emby
sudo systemctl enable emby-server.service
sudo systemctl start emby-server.service

echo "Update complete. Emby Server is now at version $latest_version."