#!/usr/bin/env bash

# Exit immediately if a command exits with a non-zero status
set -e
# Ensure the script is run with sudo/root privileges
if [ "$EUID" -ne 0 ]; then
  echo "Please run this script as root or with sudo."
  exit 1
fi
# Variables
JAVA_URL="https://storage.googleapis.com/rise-vision-led-ticker/bellsoft-jdk21.0.11%2B11-linux-i586.tar.gz"
TEMP_DIR="/tmp/java_install"
INSTALL_DIR="/usr/lib/jvm"
JDK_DIR_NAME="bellsoft-jdk21.0.11-linux-i586"
JAVA_HOME="$INSTALL_DIR/$JDK_DIR_NAME"

echo "=== System Java Environment Check ==="
# 1. Check current default Java version
echo "Current default Java version:"
if type -p java >/dev/null 2>&1; then
    # java -version outputs to stderr, so we redirect stderr to stdout to read it
    java -version 2>&1 | sed 's/^/  /'
else
    echo "  None (Java is not currently installed or not in system PATH)"
fi
echo ""
# 2. List other installed Java versions registered in update-alternatives
echo "Other registered system Java alternatives:"
if update-alternatives --get-selections 2>/dev/null | grep -q "^java "; then
    # Display the alternative paths available for the java command
    update-alternatives --display java 2>/dev/null | grep -E '^/.*bin/java' | sed 's/^/  /'
else
    echo "  None found via update-alternatives"
fi
echo "------------------------------------------------"

# 3. Prompt user to confirm installing Java 21
SHOULD_INSTALL_JAVA=false
while true; do
    read -p "Do you want to install Java 21 on this device? (yes/no): " java_choice </dev/tty
    case "$java_choice" in
        [Yy][Ee][Ss]|[Yy] )
            SHOULD_INSTALL_JAVA=true
            break
            ;;
        [Nn][Oo]|[Nn] )
            echo "Skipping Java 21 installation logic."
            break
            ;;
        * )
            echo "Please answer 'yes' or 'no'."
            ;;
    esac
done
echo "------------------------------------------------"

# 4. Conditionally download and install Java 21
if [ "$SHOULD_INSTALL_JAVA" = true ]; then
    echo "=== Starting Java 21 Installation ==="

    # Create a reliable absolute path for temporary work
    mkdir -p "$TEMP_DIR"
    cd "$TEMP_DIR"

    # Download the tarball
    echo "Downloading BellSoft JDK 21..."
    curl -k -L "$JAVA_URL" -o java_package.tar.gz

    # Prepare installation directory
    echo "Preparing installation directory at $INSTALL_DIR..."
    mkdir -p "$INSTALL_DIR"

    # Extract the package
    echo "Extracting archive..."
    # 1. Get the list of top-level directories in the tarball to find the true folder name
    EXTRACTED_DIR=$(tar -tf java_package.tar.gz | head -n 1 | cut -f1 -d"/")

    # 2. Extract into /usr/lib/jvm
    tar -xzvf java_package.tar.gz -C "$INSTALL_DIR"
    # 3. Dynamically set the absolute JAVA_HOME path based on what was actually extracted
    REAL_JAVA_HOME="$INSTALL_DIR/$EXTRACTED_DIR"
    # Set up update-alternatives to make it the default system Java
    echo "Configuring system alternatives using path: $REAL_JAVA_HOME"
    update-alternatives --install /usr/bin/java java "$REAL_JAVA_HOME/bin/java" 2000
    update-alternatives --install /usr/bin/javac javac "$REAL_JAVA_HOME/bin/javac" 2000

    # Force system to use these specific alternatives
    update-alternatives --set java "$REAL_JAVA_HOME/bin/java"
    update-alternatives --set javac "$REAL_JAVA_HOME/bin/javac"

    # Step back to a safe directory BEFORE deleting the temp folder
    cd /

    # Cleanup temporary Java files
    echo "Cleaning up temporary Java files..."
    rm -rf "$TEMP_DIR"

    # Verification
    echo "=== Java Installation Complete ==="
    echo "Verifying default Java version:"
    java -version

    echo "------------------------------------------------"
fi

exit 0
