#!/usr/bin/env bash
# ═══════════════════════════════════════════════════════════════════════════════
# Appong Workspaces — Linux Installer
# ═══════════════════════════════════════════════════════════════════════════════
#
# What this script does:
#
#   1. Detects whether Appong Workspaces is already installed
#      (system-wide or user-only).
#      If found, offers to upgrade (in-place) or uninstall.
#
#   2. If not installed, asks where to install:
#
#      System-wide  (requires sudo / root):
#        AppImage  →  /usr/local/bin/appong-workspaces
#        Icon      →  /usr/share/pixmaps/appong-workspaces.png
#        Desktop   →  /usr/share/applications/appong-workspaces.desktop
#
#      Current user only  (no root required):
#        AppImage  →  ~/.local/bin/appong-workspaces
#        Icon      →  ~/.local/share/icons/appong-workspaces.png
#        Desktop   →  ~/.local/share/applications/appong-workspaces.desktop
#
#   After installation Appong Workspaces will appear in your application
#   launcher and can be launched from a terminal with:  appong-workspaces
#
#   Note: For a user install, ~/.local/bin must be on your PATH.
#   Most modern distributions add it automatically on next login
#   if the directory exists.
#
# Usage:
#   bash install.sh
#
# ═══════════════════════════════════════════════════════════════════════════════
set -euo pipefail

APP_NAME="Appong Workspaces"
BIN_NAME="appong-workspaces"

# ── Paths ─────────────────────────────────────────────────────────────────────

SYSTEM_BIN="/usr/local/bin/${BIN_NAME}"
SYSTEM_ICON="/usr/share/pixmaps/${BIN_NAME}.png"
SYSTEM_DESKTOP="/usr/share/applications/${BIN_NAME}.desktop"

USER_BIN="${HOME}/.local/bin/${BIN_NAME}"
USER_ICON="${HOME}/.local/share/icons/${BIN_NAME}.png"
USER_DESKTOP="${HOME}/.local/share/applications/${BIN_NAME}.desktop"

# ── Locate bundled files ───────────────────────────────────────────────────────

SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"

shopt -s nullglob
_appimages=("${SCRIPT_DIR}"/*.AppImage)
shopt -u nullglob

if [ ${#_appimages[@]} -eq 0 ]; then
    echo "Error: No .AppImage file found next to install.sh."
    echo "Make sure you extracted the full release archive."
    exit 1
fi

APPIMAGE="${_appimages[0]}"
ICON="${SCRIPT_DIR}/${BIN_NAME}.png"

# ── Helpers ───────────────────────────────────────────────────────────────────

update_desktop_db() {
    local dir="$1"
    if command -v update-desktop-database &>/dev/null; then
        update-desktop-database "${dir}" 2>/dev/null || true
    fi
}

update_icon_cache() {
    local dir="$1"
    if command -v gtk-update-icon-cache &>/dev/null; then
        gtk-update-icon-cache -f -t "${dir}" 2>/dev/null || true
    fi
}

install_system() {
    echo "==> Installing system-wide (sudo required)..."

    sudo install -Dm755 "${APPIMAGE}"    "${SYSTEM_BIN}"
    sudo install -Dm644 "${ICON}"        "${SYSTEM_ICON}"

    sudo tee "${SYSTEM_DESKTOP}" > /dev/null << EOF
[Desktop Entry]
Name=${APP_NAME}
Comment=Structured web workspace manager
Exec=${SYSTEM_BIN}
Icon=${SYSTEM_ICON}
Type=Application
Categories=Utility;
Terminal=false
StartupWMClass=lv.fourapps.appong.workspaces
EOF

    update_desktop_db "$(dirname "${SYSTEM_DESKTOP}")"

    echo ""
    echo "${APP_NAME} installed system-wide."
    echo "  Launch from your application menu, or type: ${BIN_NAME}"
}

install_user() {
    echo "==> Installing for current user..."

    install -Dm755 "${APPIMAGE}"    "${USER_BIN}"
    install -Dm644 "${ICON}"        "${USER_ICON}"

    mkdir -p "$(dirname "${USER_DESKTOP}")"

    cat > "${USER_DESKTOP}" << EOF
[Desktop Entry]
Name=${APP_NAME}
Comment=Structured web workspace manager
Exec=${USER_BIN}
Icon=${USER_ICON}
Type=Application
Categories=Utility;
Terminal=false
StartupWMClass=lv.fourapps.appong.workspaces
EOF

    update_desktop_db "$(dirname "${USER_DESKTOP}")"
    update_icon_cache "${HOME}/.local/share/icons"

    echo ""
    echo "${APP_NAME} installed for user '${USER}'."
    echo "  Launch from your application menu, or type: ${BIN_NAME}"

    if [[ ":${PATH}:" != *":${HOME}/.local/bin:"* ]]; then
        echo ""
        echo "  Note: ~/.local/bin is not currently on your PATH."
        echo "  Log out and back in (or run 'source ~/.profile') for"
        echo "  the '${BIN_NAME}' terminal command to become available."
    fi
}

uninstall_system() {
    echo "==> Removing system-wide installation (requires sudo)..."
    sudo rm -f "${SYSTEM_BIN}" "${SYSTEM_ICON}" "${SYSTEM_DESKTOP}"
    update_desktop_db "$(dirname "${SYSTEM_DESKTOP}")"
    echo "    Removed."
}

uninstall_user() {
    echo "==> Removing user installation..."
    rm -f "${USER_BIN}" "${USER_ICON}" "${USER_DESKTOP}"
    update_desktop_db "$(dirname "${USER_DESKTOP}")"
    update_icon_cache "${HOME}/.local/share/icons"
    echo "    Removed."
}

# ── Check for existing installation ───────────────────────────────────────────

SYSTEM_INSTALLED=false
USER_INSTALLED=false

[ -f "${SYSTEM_BIN}" ]  && SYSTEM_INSTALLED=true
[ -f "${USER_BIN}" ]    && USER_INSTALLED=true

if ${SYSTEM_INSTALLED} || ${USER_INSTALLED}; then
    echo ""
    echo "${APP_NAME} is already installed:"
    ${SYSTEM_INSTALLED} && echo "  System-wide : ${SYSTEM_BIN}"
    ${USER_INSTALLED}   && echo "  User        : ${USER_BIN}"
    echo ""
    echo "What would you like to do?"
    echo "  1) Upgrade"
    echo "  2) Uninstall"
    echo ""

    CHOICE=""
    while true; do
        read -r -p "Choice [1/2] (default: 1): " CHOICE
        CHOICE="${CHOICE:-1}"
        case "${CHOICE}" in
            1|2) break ;;
            *) echo "Please enter 1 or 2." ;;
        esac
    done

    echo ""

    if [ "${CHOICE}" = "2" ]; then
        ${SYSTEM_INSTALLED} && uninstall_system
        ${USER_INSTALLED}   && uninstall_user
        echo ""
        echo "${APP_NAME} has been uninstalled."
        exit 0
    fi

    ${SYSTEM_INSTALLED} && install_system
    ${USER_INSTALLED}   && install_user
    echo ""
    exit 0
fi

# ── Fresh install: choose scope ──────────────────────────────────────────────

echo ""
echo "Install ${APP_NAME} for:"
echo "  1) System-wide  (all users, requires sudo)"
echo "  2) Current user only  (no root required)"
echo ""

SCOPE=""
while true; do
    read -r -p "Choice [1/2] (default: 2): " SCOPE
    SCOPE="${SCOPE:-2}"
    case "${SCOPE}" in
        1|2) break ;;
        *) echo "Please enter 1 or 2." ;;
    esac
done

echo ""

if [ "${SCOPE}" = "1" ]; then
    install_system
else
    install_user
fi

echo ""
