#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# ──────────────────────────────────────────────────────────────────────────────
# Private Archive — Meta-bundle Installer (Linux / macOS / *BSD)
#
# Installs the full Private Archive client (backend daemon + CLI + desktop app
# where available) and registers the backend with the host's init system so it
# starts automatically on boot.
#
# Usage:
#   sudo ./install.sh           # system-wide
#   ./install.sh --user         # per-user, no root
#   ./install.sh --no-service   # copy binaries only, skip service registration
# ──────────────────────────────────────────────────────────────────────────────
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

USER_INSTALL=false
INSTALL_SERVICE=true
PREFIX=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        --user)        USER_INSTALL=true; shift ;;
        --no-service)  INSTALL_SERVICE=false; shift ;;
        --prefix)      PREFIX="$2"; shift 2 ;;
        -h|--help)
            sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//'
            exit 0 ;;
        *) echo "Unknown option: $1" >&2; exit 1 ;;
    esac
done

if [[ -z "$PREFIX" ]]; then
    if [[ "$USER_INSTALL" == "true" ]]; then
        PREFIX="$HOME/.local"
    else
        PREFIX="/usr/local"
    fi
fi

BIN_DIR="$PREFIX/bin"
SHARE_DIR="$PREFIX/share"
APPLICATIONS_DIR="$SHARE_DIR/applications"

OS="$(uname -s | tr '[:upper:]' '[:lower:]')"

echo "Private Archive — Installer"
echo "═══════════════════════════"
echo "Detected OS:       $OS"
echo "Install prefix:    $PREFIX"
echo "Mode:              $([[ $USER_INSTALL == true ]] && echo "user" || echo "system")"
echo "Register service:  $INSTALL_SERVICE"
echo

# ── Copy binaries ────────────────────────────────────────────────────────────
mkdir -p "$BIN_DIR"

for bin in "$SCRIPT_DIR"/bin/*; do
    [[ -f "$bin" && -x "$bin" ]] || continue
    name="$(basename "$bin")"
    install -m 0755 "$bin" "$BIN_DIR/$name"
    echo "  ✔ Installed $BIN_DIR/$name"
done

# ── Shell completions ───────────────────────────────────────────────────────
if [[ -d "$SCRIPT_DIR/share" ]]; then
    if [[ -f "$SCRIPT_DIR/share/bash-completion/completions/privatebackup" ]]; then
        mkdir -p "$SHARE_DIR/bash-completion/completions"
        install -m 0644 "$SCRIPT_DIR/share/bash-completion/completions/privatebackup" \
                        "$SHARE_DIR/bash-completion/completions/privatebackup"
        echo "  ✔ Installed bash completions"
    fi
    if [[ -f "$SCRIPT_DIR/share/zsh/site-functions/_privatebackup" ]]; then
        mkdir -p "$SHARE_DIR/zsh/site-functions"
        install -m 0644 "$SCRIPT_DIR/share/zsh/site-functions/_privatebackup" \
                        "$SHARE_DIR/zsh/site-functions/_privatebackup"
        echo "  ✔ Installed zsh completions"
    fi
    if [[ -f "$SCRIPT_DIR/share/fish/vendor_completions.d/privatebackup.fish" ]]; then
        mkdir -p "$SHARE_DIR/fish/vendor_completions.d"
        install -m 0644 "$SCRIPT_DIR/share/fish/vendor_completions.d/privatebackup.fish" \
                        "$SHARE_DIR/fish/vendor_completions.d/privatebackup.fish"
        echo "  ✔ Installed fish completions"
    fi
fi

# ── Desktop app ─────────────────────────────────────────────────────────────
# On macOS we install the .app bundle. On Linux we drop a .desktop entry that
# launches the binary in $BIN_DIR. On *BSD we just copy the binary if present.
if [[ -d "$SCRIPT_DIR/desktop" ]]; then
    case "$OS" in
        darwin)
            # Look for any .app bundle in desktop/.
            for app in "$SCRIPT_DIR"/desktop/*.app; do
                [[ -d "$app" ]] || continue
                target="/Applications/$(basename "$app")"
                if [[ "$USER_INSTALL" == "true" ]]; then
                    target="$HOME/Applications/$(basename "$app")"
                    mkdir -p "$HOME/Applications"
                fi
                rm -rf "$target"
                cp -R "$app" "$target"
                echo "  ✔ Installed $(basename "$app") → $target"
            done
            ;;
        linux)
            if [[ -f "$SCRIPT_DIR/desktop/PrivateBackup" ]]; then
                install -m 0755 "$SCRIPT_DIR/desktop/PrivateBackup" "$BIN_DIR/PrivateBackup"
                echo "  ✔ Installed desktop binary → $BIN_DIR/PrivateBackup"
            fi
            if [[ -f "$SCRIPT_DIR/desktop/private-archive.desktop" ]]; then
                mkdir -p "$APPLICATIONS_DIR"
                # Rewrite Exec= to point at the actual install path.
                sed "s|^Exec=.*|Exec=$BIN_DIR/PrivateBackup|" \
                    "$SCRIPT_DIR/desktop/private-archive.desktop" \
                    > "$APPLICATIONS_DIR/private-archive.desktop"
                chmod 0644 "$APPLICATIONS_DIR/private-archive.desktop"
                echo "  ✔ Installed .desktop entry"
            fi
            ;;
        *)
            # *BSD or other unix: copy raw binary if present.
            if [[ -f "$SCRIPT_DIR/desktop/PrivateBackup" ]]; then
                install -m 0755 "$SCRIPT_DIR/desktop/PrivateBackup" "$BIN_DIR/PrivateBackup"
                echo "  ✔ Installed desktop binary → $BIN_DIR/PrivateBackup"
            else
                echo "  ⚠ No prebuilt desktop binary for $OS — build from source if needed."
            fi
            ;;
    esac
fi

# ── Register the backend with the host's init system ───────────────────────
BACKEND_BIN="$BIN_DIR/privatebackup-backend"

if [[ "$INSTALL_SERVICE" != "true" ]]; then
    echo
    echo "Skipping service registration (--no-service)."
elif [[ ! -x "$BACKEND_BIN" ]]; then
    echo
    echo "  ⚠ Backend binary not found at $BACKEND_BIN — service auto-start NOT configured."
else
    echo
    echo "Registering backend service (init-system auto-detected)..."
    if [[ "$USER_INSTALL" == "true" ]]; then
        if "$BACKEND_BIN" service install 2>&1; then
            echo "  ✔ User-level service registered"
        else
            echo "  ⚠ Service registration failed — run '$BACKEND_BIN service install' manually."
        fi
    else
        if "$BACKEND_BIN" service install --system 2>&1; then
            echo "  ✔ System-wide service registered"
        else
            echo "  ⚠ Service registration failed — run 'sudo $BACKEND_BIN service install --system' manually."
        fi
    fi
fi

echo
echo "Installation complete."
echo
echo "Next steps:"
echo "  privatebackup-backend service status   # verify the service is registered"
echo "  privatebackup --help                   # see the CLI"
if [[ "$USER_INSTALL" == "true" && ":$PATH:" != *":$BIN_DIR:"* ]]; then
    echo
    echo "Note: $BIN_DIR is not on your PATH. Add it with:"
    echo "  export PATH=\"$BIN_DIR:\$PATH\""
fi
