#!/bin/bash -eu
# SPDX-FileCopyrightText: 2025 Bart van de Lint
# SPDX-License-Identifier: MPL-2.0

# This script updates Julia packages, creating a version-specific Manifest file.
# It checks for a local Python/Matplotlib installation and can use Julia's
# Conda as a fallback.
#
# Usage:
#   ./update_script.sh              # Uses the default Julia version
#   ./update_script.sh +1.12        # Uses Julia v1.12
#   ./update_script.sh --default    # Creates a .default manifest copy

# --- 1. Argument Parsing and Version Determination ---
make_default=false
julia_channel_arg=""

# Loop through all arguments to find our specific flags
for arg in "$@"; do
  case $arg in
    --default)
      make_default=true
      ;;
    +*)
      julia_channel_arg=$arg
      ;;
  esac
done

julia_major=""
if [[ -n "$julia_channel_arg" ]]; then
    # Use version from +<version> argument
    julia_major="${julia_channel_arg#+}"
else
    # Fallback to the default julia version
    julia_major=$(julia --version | cut -d' ' -f3 | cut -d'.' -f1,2)
fi

# Construct the Julia command, including the version specifier if provided
JULIA_CMD="julia"
if [[ -n "$julia_channel_arg" ]]; then
    JULIA_CMD="julia $julia_channel_arg"
fi
echo "Targeting Julia v${julia_major}..."

# --- 2. Check for Python and Matplotlib ---
# Find python3 executable. If it has matplotlib, export it for PyCall.
# Otherwise, ask the user if we should use Conda.
PYTHON_PATH=$(which python3 || true)
if [[ -n "$PYTHON_PATH" && -x "$PYTHON_PATH" ]] && $PYTHON_PATH -c "import matplotlib" &> /dev/null; then
    echo "✅ Found Python with Matplotlib at $PYTHON_PATH. Using this installation."
    export PYTHON=$PYTHON_PATH
else
    if [[ -n "$PYTHON_PATH" ]]; then
        echo "⚠️ Python was found, but it's missing the 'matplotlib' library."
    else
        echo "⚠️ Python 3 was not found in your PATH."
    fi
    read -p "Do you want to let Julia's Conda install a local version for you? (y/n): " choice
    case "$choice" in
        y|Y)
            export PYTHON=""
            echo "Proceeding with Conda installation via Julia."
            ;;
        n|N)
            echo "Exiting without installing dependencies."
            exit 1
            ;;
        *)
            echo "Invalid choice. Exiting."
            exit 1
            ;;
    esac
fi

# --- 3. Backup Existing Manifest Files ---
echo "Preparing to update packages..."
export JULIA_PKG_SERVER_REGISTRY_PREFERENCE="eager"

MANIFEST_VERSION_FILE="Manifest-v${julia_major}.toml"

# Move existing manifest files to .bak to ensure a clean update
mv -f Manifest.toml Manifest.toml.bak 2>/dev/null || true
mv -f "$MANIFEST_VERSION_FILE" "${MANIFEST_VERSION_FILE}.bak" 2>/dev/null || true

# --- 4. Update Julia Packages ---
echo "Adding/updating Julia packages. This may take a while..."
$JULIA_CMD --startup-file=no -e "using Pkg; Pkg.add(\"TestEnv\")"
$JULIA_CMD --startup-file=no --project -e '
    using TestEnv
    println("--> Activating environment...");
    TestEnv.activate()
    using Pkg
    println("--> Adding PyCall...")
    Pkg.add("PyCall");
    println("--> Building PyCall...");
    Pkg.build("PyCall");
    println("PyCall configured.");

    # Only add Conda and matplotlib if PYTHON is not set in the environment
    if get(ENV, "PYTHON", "") == ""
        println("--> Installing Conda dependencies...");
        Pkg.add("Conda");
        using Conda;
        Conda.add("matplotlib");
        println("Conda and matplotlib installed.");
    end;

    println("--> Loading ControlPlots...")
    using ControlPlots
    println("--> Running final package update...");
    Pkg.update();
    println("Package update complete.");
'

# --- 5. Finalize Manifest ---
echo "Creating final manifest file..."
mv Manifest.toml "$MANIFEST_VERSION_FILE"
echo "✅ Update successful. New manifest created at ${MANIFEST_VERSION_FILE}"

# --- 6. Create Default Manifest if requested ---
if [ "$make_default" = true ]; then
  DEFAULT_FILE="${MANIFEST_VERSION_FILE}.default"
  echo "--> --default flag detected. Creating default manifest..."
  cp "$MANIFEST_VERSION_FILE" "$DEFAULT_FILE"
  echo "✅ Default manifest created at ${DEFAULT_FILE}"
fi
