#!/bin/bash

# Exit immediately if a command exits with a non-zero status.
set -e

# --- Configuration ---
# Gitea credentials should be set as environment variables for security
# export GITEA_USERNAME="your_gitea_username"
# export GITEA_TOKEN="your_gitea_token" 
# or use .netrc file for authentication

# Gitea repository URL
GITEA_REPO_URL="https://gitea.wpjones.com/wjones/pgsql-jellyfin.git"

# Branch to use
BRANCH="main"

# .NET Solution file
SOLUTION_FILE="Jellyfin.sln"

# Publish directory
PUBLISH_DIR="/opt/jellyfin"

# Log and config directories
LOG_DIR="/var/log/jellyfin"
CONFIG_DIR="/etc/jellyfin"

# --- Functions ---
build_and_publish() {
    echo "Building and publishing the .NET project..."

    # Restore, build, and publish the .NET project
    if ! dotnet restore "$SOLUTION_FILE" -r linux-x64 || \
       ! dotnet build "$SOLUTION_FILE" --configuration Release || \
       ! dotnet publish "Jellyfin.Server/Jellyfin.Server.csproj" --configuration Release --self-contained true -r linux-x64 --output "$PUBLISH_DIR"; then
        echo "Error: Build or publish failed." >&2
        return 1
    fi

    echo "Project built and published successfully to the '$PUBLISH_DIR' directory."
    return 0
}

# --- Service Management ---
SERVICE_NAME="jellyfin.service"


# Check if Jellyfin service is running and stop it
if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "Jellyfin service is running. Stopping it now..."
    sudo systemctl stop "$SERVICE_NAME"
    echo "Jellyfin service stopped."
fi

# --- Script ---

# Stop Jellyfin service if it's running
if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "Jellyfin service is running. Stopping it now..."
    sudo systemctl stop "$SERVICE_NAME"
    echo "Jellyfin service stopped."
fi

echo "Logging in to Gitea and fetching latest changes..."

# Use Git to pull the latest changes.
# This assumes you have already cloned the repository and are in the repo directory.
# For authentication, Git can use a .netrc file, or you can configure Git to use a credential helper.
# For simplicity, this script assumes that your environment is already configured to authenticate with Gitea.
git checkout "$BRANCH"
git pull origin "$BRANCH"

echo "Latest changes fetched successfully."

# Attempt to build and publish. If it fails, exit.
if ! build_and_publish; then
    echo "Build and publish failed. Not starting Jellyfin service."
    exit 1
fi

echo "Checking for required directories..."

if [ ! -d "$LOG_DIR" ]; then
    echo "Creating log directory: $LOG_DIR"
    mkdir -p "$LOG_DIR"
fi

if [ ! -d "$CONFIG_DIR" ]; then
    echo "Creating config directory: $CONFIG_DIR"
    mkdir -p "$CONFIG_DIR"
fi

echo "Directory check complete."

# Restart Jellyfin service
echo "Restarting Jellyfin service..."
sudo systemctl start "$SERVICE_NAME"
echo "Jellyfin service restarted successfully."

