#!/usr/bin/env bash

set -euo pipefail

JRE_ROOT="${HOME}/.cache/velo.port/jre/21"

error_exit() {
    echo "WARNUNG: Die velo.port-Installation scheint beschädigt zu sein. Die JRE kann nicht ermittelt werden." >&2
    exit 1
}

[[ -d "$JRE_ROOT" ]] || error_exit

JRE_PATH="$(find "$JRE_ROOT" -mindepth 1 -maxdepth 1 -type d | sort | head -n 1)"

[[ -n "$JRE_PATH" ]] || error_exit

JAVA_FILE="${JRE_PATH}/bin/java"

[[ -x "$JAVA_FILE" ]] || error_exit

SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

BIN_FOLDER_NAME="lib"
JAR_NAME="vp-launcher.jar"
ICON_NAME="vplauncher.png"

SOURCE_BIN_FOLDER="${SOURCE_DIR}/${BIN_FOLDER_NAME}"
SOURCE_JAR_FILE="${SOURCE_DIR}/${JAR_NAME}"
SOURCE_ICON_FILE="${SOURCE_DIR}/${ICON_NAME}"

TARGET_DIR="${HOME}/.cache/velo.port/app/vp-launcher"
TARGET_BIN_FOLDER="${TARGET_DIR}/${BIN_FOLDER_NAME}"
TARGET_JAR_FILE="${TARGET_DIR}/${JAR_NAME}"
TARGET_ICON_FILE="${TARGET_DIR}/${ICON_NAME}"

APPLICATIONS_DIR="${XDG_DATA_HOME:-${HOME}/.local/share}/applications"

if command -v xdg-user-dir >/dev/null 2>&1; then
    DESKTOP_DIR="$(xdg-user-dir DESKTOP)"
else
    DESKTOP_DIR="${HOME}/Desktop"
fi

DESKTOP_FILE_NAME="velo.port Schnellstart.desktop"

LAUNCHER_APPLICATION_FILE="${APPLICATIONS_DIR}/${DESKTOP_FILE_NAME}"
LAUNCHER_DESKTOP_FILE="${DESKTOP_DIR}/${DESKTOP_FILE_NAME}"

mkdir -p "$TARGET_DIR"

if [[ -d "$SOURCE_BIN_FOLDER" ]]; then
    rm -rf "$TARGET_BIN_FOLDER"
    cp -a "$SOURCE_BIN_FOLDER" "$TARGET_BIN_FOLDER"
else
    echo "WARNUNG: Quellordner nicht gefunden: $SOURCE_BIN_FOLDER" >&2
fi

if [[ -f "$SOURCE_JAR_FILE" ]]; then
    cp -f "$SOURCE_JAR_FILE" "$TARGET_JAR_FILE"
else
    echo "WARNUNG: Quelldatei nicht gefunden: $SOURCE_JAR_FILE" >&2
fi

if [[ -f "$SOURCE_ICON_FILE" ]]; then
    cp -f "$SOURCE_ICON_FILE" "$TARGET_ICON_FILE"
else
    echo "WARNUNG: Quelldatei nicht gefunden: $SOURCE_ICON_FILE" >&2
fi

mkdir -p "$APPLICATIONS_DIR"

create_desktop_file() {
    local file="$1"

    cat > "$file" <<EOF
[Desktop Entry]
Version=1.0
Type=Application
Name=velo.port Schnellstart
Comment=velo.port Schnellstart
Exec=${JAVA_FILE} -jar "${TARGET_JAR_FILE}" --force-window
Path=${TARGET_DIR}
Icon=${TARGET_ICON_FILE}
Terminal=false
Categories=Utility;
EOF

    chmod +x "$file"
}

create_desktop_file "$LAUNCHER_APPLICATION_FILE"

if [[ -d "$DESKTOP_DIR" ]]; then
    create_desktop_file "$LAUNCHER_DESKTOP_FILE"
fi

echo "Installation abgeschlossen."
