#!/bin/bash

# Define your custom Plex config directory
CUSTOM_PLEX_CONFIG="/mnt/machine-spirit/configs/plex"

# Update and upgrade system packages
echo "Updating system packages..."
sudo apt update
sudo apt full-upgrade -y

# Install prerequisites
echo "Installing prerequisites..."
sudo apt install -y apt-transport-https curl

# Add Plex official repository GPG key and repo
echo "Adding Plex repository..."
curl https://downloads.plex.tv/plex-keys/PlexSign.key | gpg --dearmor | sudo tee /usr/share/keyrings/plex-archive-keyring.gpg > /dev/null

echo "deb [signed-by=/usr/share/keyrings/plex-archive-keyring.gpg] https://downloads.plex.tv/repo/deb public main" | sudo tee /etc/apt/sources.list.d/plexmediaserver.list

# Update package lists with Plex repo
sudo apt update

# Install Plex Media Server
echo "Installing Plex Media Server..."
sudo apt install -y plexmediaserver

# Stop Plex service before moving config
sudo systemctl stop plexmediaserver

# Move current Plex config to custom location
echo "Moving Plex config to custom directory..."
sudo rsync -av /var/lib/plexmediaserver/ "$CUSTOM_PLEX_CONFIG"/

# Backup and remove existing config directory and create symlink
echo "Setting up symlink from default location to custom config path..."
sudo mv /var/lib/plexmediaserver /var/lib/plexmediaserver.bak
sudo ln -s "$CUSTOM_PLEX_CONFIG" /var/lib/plexmediaserver

# Set correct permissions
echo "Setting permissions for Plex user on custom directory..."
sudo chown -R plex:plex "$CUSTOM_PLEX_CONFIG"

# Start Plex service
sudo systemctl start plexmediaserver
sudo systemctl enable plexmediaserver

echo "Plex Media Server installation complete."
echo "Access the Plex Web UI at http://<your_pi_ip>:32400/web"
