#!/usr/bin/env sh
set -eu

# ==============================================================================
# PasteMesh Official Unified Installer
# Target Domain: pastemesh.net
#
# Usage:
#   curl -fsSL https://pastemesh.net/install.sh | sh
#   curl -fsSL https://pastemesh.net/install.sh | sh -s -- --engine=desktop
#   curl -fsSL https://pastemesh.net/install.sh | sh -s -- --engine=daemon
#   sh ./install.sh [--engine=desktop|daemon] [--prefix=/path]
# ==============================================================================

VERSION="0.13.0"
BASE_URL="https://pastemesh.net/releases"
FALLBACK_URL="https://codeberg.org/pastemesh/pastemesh/releases/download/v${VERSION}"

SELECTED_ENGINE=""
INSTALL_PREFIX=""
NO_SYSTEMD=0
UNINSTALL=0
VERBOSE=0

# Parse arguments
while [ $# -gt 0 ]; do
    case "$1" in
        --engine=*)
            SELECTED_ENGINE="${1#*=}"
            ;;
        --engine)
            shift
            if [ $# -gt 0 ]; then SELECTED_ENGINE="$1"; fi
            ;;
        --prefix=*)
            INSTALL_PREFIX="${1#*=}"
            ;;
        --prefix)
            shift
            if [ $# -gt 0 ]; then INSTALL_PREFIX="$1"; fi
            ;;
        --version=*)
            VERSION="${1#*=}"
            ;;
        --no-systemd)
            NO_SYSTEMD=1
            ;;
        --uninstall)
            UNINSTALL=1
            ;;
        -v|--verbose)
            VERBOSE=1
            ;;
        -h|--help)
            echo "PasteMesh Universal Installer v${VERSION}"
            echo ""
            echo "Usage: curl -fsSL https://pastemesh.net/install.sh | sh [ -s -- [options] ]"
            echo ""
            echo "Options:"
            echo "  --engine=daemon|desktop   Select default active engine (default: auto-detected)"
            echo "  --prefix=DIR              Custom install root prefix (default: /usr/local or ~/.local)"
            echo "  --version=X.Y.Z           Install a specific release version"
            echo "  --no-systemd              Skip systemd user service registration"
            echo "  --uninstall               Stop services and remove PasteMesh binaries & launchers"
            echo "  -v, --verbose             Display verbose installation diagnostics"
            echo "  -h, --help                Show this help screen"
            exit 0
            ;;
        *)
            ;;
    esac
    shift || true
done

if [ "$UNINSTALL" -eq 1 ]; then
    echo "=========================================================="
    echo "    Uninstalling PasteMesh                                "
    echo "=========================================================="
    if command -v systemctl >/dev/null 2>&1; then
        systemctl --user disable --now pastemesh.service 2>/dev/null || true
    fi
    pkill -f "^/[^ ]*/pastemesh .*daemon" 2>/dev/null || true
    pkill -f "^/[^ ]*/pastemesh .*tray" 2>/dev/null || true
    pkill -f "^/[^ ]*/pastemesh-desktop" 2>/dev/null || true

    if [ -n "$INSTALL_PREFIX" ]; then
        TARGET_BIN="$INSTALL_PREFIX/bin"
        TARGET_LIB="$INSTALL_PREFIX/lib/pastemesh"
    elif [ "$(id -u)" -eq 0 ]; then
        TARGET_BIN="/usr/local/bin"
        TARGET_LIB="/usr/local/lib/pastemesh"
    else
        TARGET_BIN="$HOME/.local/bin"
        TARGET_LIB="$HOME/.local/lib/pastemesh"
    fi

    rm -f "$TARGET_BIN/pastemesh" "$TARGET_BIN/pastemesh-desktop"
    rm -rf "$TARGET_LIB"
    rm -f "$HOME/.config/systemd/user/pastemesh.service"
    rm -f "$HOME/.config/autostart/pastemesh-tray.desktop"
    rm -f "$HOME/.local/share/applications/pastemesh.desktop" "$HOME/.local/share/applications/pastemesh-desktop.desktop"
    if command -v systemctl >/dev/null 2>&1; then
        systemctl --user daemon-reload 2>/dev/null || true
    fi
    echo "✓ PasteMesh binaries, systemd user service, and desktop launchers removed."
    echo "  (Your encrypted vault at ~/.config/pastemesh was preserved.)"
    exit 0
fi

echo ""
echo "=========================================================="
echo "    Installing PasteMesh v${VERSION} (pastemesh.net)      "
echo "=========================================================="

# 1. Detect Operating System and Architecture
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"

IS_CROSTINI=0
case "$OS" in
    linux)
        OS_PREFIX="linux"
        if [ -f /dev/.cros_milestone ] || [ -n "${SOMMELIER_VERSION:-}" ] || grep -qi "chromiumos\|cros" /proc/version 2>/dev/null; then
            IS_CROSTINI=1
        fi
        ;;
    darwin)
        OS_PREFIX="osx"
        ;;
    msys*|mingw*|cygwin*)
        echo ""
        echo "Detected Windows environment!"
        echo "Please run the official Windows installer in PowerShell:"
        echo "  irm https://pastemesh.net/install.ps1 | iex"
        echo ""
        exit 1
        ;;
    *)
        echo "Error: Operating system '$OS' is currently unsupported."
        exit 1
        ;;
esac

case "$ARCH" in
    x86_64|amd64)
        ARCH_SUFFIX="${OS_PREFIX}-x64"
        ;;
    aarch64|arm64)
        ARCH_SUFFIX="${OS_PREFIX}-arm64"
        ;;
    *)
        echo "Error: Architecture '$ARCH' is currently unsupported."
        exit 1
        ;;
esac

TARBALL_NAME="pastemesh-v${VERSION}-${ARCH_SUFFIX}.tar.gz"

# 2. Determine installation target directories
if [ -n "$INSTALL_PREFIX" ]; then
    INSTALL_BIN="$INSTALL_PREFIX/bin"
    INSTALL_LIB="$INSTALL_PREFIX/lib/pastemesh"
elif [ "$(id -u)" -eq 0 ]; then
    INSTALL_BIN="/usr/local/bin"
    INSTALL_LIB="/usr/local/lib/pastemesh"
else
    INSTALL_BIN="$HOME/.local/bin"
    INSTALL_LIB="$HOME/.local/lib/pastemesh"
fi

SYSTEMD_DIR="$HOME/.config/systemd/user"
mkdir -p "$INSTALL_BIN" "$INSTALL_LIB"

# 3. Acquire binaries
TMP_DIR="$(mktemp -d 2>/dev/null || mktemp -d -t 'pastemesh-install')"
trap 'rm -rf "$TMP_DIR"' EXIT INT TERM

SCRIPT_DIR=""
if [ -n "${0:-}" ] && [ -f "$0" ] && [ "$0" != "sh" ] && [ "$0" != "bash" ]; then
    SCRIPT_DIR="$(cd "$(dirname "$0")" 2>/dev/null && pwd || true)"
fi

COPIED_FROM_LOCAL=0

# Check if running locally alongside extracted bundle binaries
if [ -n "$SCRIPT_DIR" ] && [ -f "$SCRIPT_DIR/bundle/pastemesh" ]; then
    echo "• Found local bundle binaries in $SCRIPT_DIR/bundle, copying..."
    cp -f "$SCRIPT_DIR/bundle/pastemesh" "$INSTALL_LIB/"
    if [ -f "$SCRIPT_DIR/bundle/pastemesh-desktop" ]; then cp -f "$SCRIPT_DIR/bundle/pastemesh-desktop" "$INSTALL_LIB/"; fi
    COPIED_FROM_LOCAL=1
elif [ -n "$SCRIPT_DIR" ] && [ -f "$SCRIPT_DIR/pastemesh" ]; then
    echo "• Found local bundle binaries in $SCRIPT_DIR, copying..."
    cp -f "$SCRIPT_DIR/pastemesh" "$INSTALL_LIB/"
    if [ -f "$SCRIPT_DIR/pastemesh-desktop" ]; then cp -f "$SCRIPT_DIR/pastemesh-desktop" "$INSTALL_LIB/"; fi
    COPIED_FROM_LOCAL=1
# Check if running inside pastemesh repository workspace
elif [ -d "/datadisk/Repos/pastemesh/dist/bundle" ] && [ -f "/datadisk/Repos/pastemesh/dist/bundle/pastemesh" ]; then
    echo "• Found local repository bundle in /datadisk/Repos/pastemesh/dist/bundle, copying..."
    cp -f /datadisk/Repos/pastemesh/dist/bundle/pastemesh "$INSTALL_LIB/"
    cp -f /datadisk/Repos/pastemesh/dist/bundle/pastemesh-desktop "$INSTALL_LIB/" 2>/dev/null || true
    COPIED_FROM_LOCAL=1
fi

if [ "$COPIED_FROM_LOCAL" -eq 0 ]; then
    echo "• Downloading release archive: ${TARBALL_NAME}..."
    DOWNLOAD_SUCCESS=0

    # Try curl first
    if command -v curl >/dev/null 2>&1; then
        if curl -fsSL "${BASE_URL}/${TARBALL_NAME}" -o "${TMP_DIR}/${TARBALL_NAME}" 2>/dev/null; then
            DOWNLOAD_SUCCESS=1
        elif curl -fsSL "${FALLBACK_URL}/${TARBALL_NAME}" -o "${TMP_DIR}/${TARBALL_NAME}" 2>/dev/null; then
            DOWNLOAD_SUCCESS=1
        fi
    elif command -v wget >/dev/null 2>&1; then
        if wget -q "${BASE_URL}/${TARBALL_NAME}" -O "${TMP_DIR}/${TARBALL_NAME}" 2>/dev/null; then
            DOWNLOAD_SUCCESS=1
        elif wget -q "${FALLBACK_URL}/${TARBALL_NAME}" -O "${TMP_DIR}/${TARBALL_NAME}" 2>/dev/null; then
            DOWNLOAD_SUCCESS=1
        fi
    fi

    if [ "$DOWNLOAD_SUCCESS" -eq 1 ] && [ -f "${TMP_DIR}/${TARBALL_NAME}" ]; then
        # Verify SHA-256 against SHA256SUMS when available
        SUMS_OK=0
        if command -v curl >/dev/null 2>&1; then
            if curl -fsSL "${BASE_URL}/SHA256SUMS" -o "${TMP_DIR}/SHA256SUMS" 2>/dev/null; then
                SUMS_OK=1
            elif curl -fsSL "${FALLBACK_URL}/SHA256SUMS" -o "${TMP_DIR}/SHA256SUMS" 2>/dev/null; then
                SUMS_OK=1
            fi
        elif command -v wget >/dev/null 2>&1; then
            if wget -q "${BASE_URL}/SHA256SUMS" -O "${TMP_DIR}/SHA256SUMS" 2>/dev/null; then
                SUMS_OK=1
            elif wget -q "${FALLBACK_URL}/SHA256SUMS" -O "${TMP_DIR}/SHA256SUMS" 2>/dev/null; then
                SUMS_OK=1
            fi
        fi

        if [ "$SUMS_OK" -eq 1 ] && [ -f "${TMP_DIR}/SHA256SUMS" ]; then
            EXPECTED_SHA="$(awk -v f="$TARBALL_NAME" '$2 == f || $2 == ("*" f) { print $1; exit }' "${TMP_DIR}/SHA256SUMS")"
            if [ -n "$EXPECTED_SHA" ]; then
                ACTUAL_SHA=""
                if command -v sha256sum >/dev/null 2>&1; then
                    ACTUAL_SHA="$(sha256sum "${TMP_DIR}/${TARBALL_NAME}" | awk '{print $1}')"
                elif command -v shasum >/dev/null 2>&1; then
                    ACTUAL_SHA="$(shasum -a 256 "${TMP_DIR}/${TARBALL_NAME}" | awk '{print $1}')"
                fi
                if [ -n "$ACTUAL_SHA" ]; then
                    if [ "$ACTUAL_SHA" != "$EXPECTED_SHA" ]; then
                        echo "Error: SHA-256 checksum mismatch for ${TARBALL_NAME}!" >&2
                        echo "  Expected: ${EXPECTED_SHA}" >&2
                        echo "  Actual:   ${ACTUAL_SHA}" >&2
                        exit 1
                    fi
                    echo "• Verified SHA-256 checksum (${ACTUAL_SHA})"
                fi
            fi
        fi

        echo "• Unpacking release archive..."
        tar -xzf "${TMP_DIR}/${TARBALL_NAME}" -C "$TMP_DIR"
        
        # Copy binaries to installation library directory
        if [ -f "${TMP_DIR}/pastemesh" ]; then cp -f "${TMP_DIR}/pastemesh" "$INSTALL_LIB/"; fi
        if [ -f "${TMP_DIR}/pastemesh-desktop" ]; then cp -f "${TMP_DIR}/pastemesh-desktop" "$INSTALL_LIB/"; fi
    else
        echo "Error: Failed to download release bundle from https://pastemesh.net."
        echo "Please check your internet connection or download manually from: https://pastemesh.net"
        exit 1
    fi
fi

# Ensure all binaries are executable
chmod +x "$INSTALL_LIB"/* 2>/dev/null || true

# 4. Create launcher symlinks in bin directory
ln -sf "$INSTALL_LIB/pastemesh" "$INSTALL_BIN/pastemesh"
echo "• Linked: $INSTALL_BIN/pastemesh -> $INSTALL_LIB/pastemesh"

if [ -f "$INSTALL_LIB/pastemesh-desktop" ]; then
    ln -sf "$INSTALL_LIB/pastemesh-desktop" "$INSTALL_BIN/pastemesh-desktop"
    echo "• Linked: $INSTALL_BIN/pastemesh-desktop -> $INSTALL_LIB/pastemesh-desktop"
fi

# 5. Install Desktop Icons and Application Entry
ICON_DIR="${HOME}/.local/share/icons/hicolor"
APPS_DIR="${HOME}/.local/share/applications"
if [ "$(id -u)" -eq 0 ]; then
    ICON_DIR="/usr/share/icons/hicolor"
    APPS_DIR="/usr/share/applications"
fi

ICON_SRC=""
if [ -d "${SCRIPT_DIR}/../assets/icons" ]; then
    ICON_SRC="${SCRIPT_DIR}/../assets/icons"
elif [ -d "/datadisk/Repos/pastemesh/assets/icons" ]; then
    ICON_SRC="/datadisk/Repos/pastemesh/assets/icons"
fi

if [ -n "$ICON_SRC" ] && [ -d "$ICON_SRC" ]; then
    mkdir -p "${ICON_DIR}/scalable/apps" "${ICON_DIR}/symbolic/apps" "${APPS_DIR}" 2>/dev/null || true
    for sz in 16 24 32 48 64 128 256 512; do
        if [ -f "${ICON_SRC}/pastemesh_${sz}.png" ]; then
            mkdir -p "${ICON_DIR}/${sz}x${sz}/apps" 2>/dev/null || true
            cp -f "${ICON_SRC}/pastemesh_${sz}.png" "${ICON_DIR}/${sz}x${sz}/apps/pastemesh.png" 2>/dev/null || true
            cp -f "${ICON_SRC}/pastemesh_${sz}.png" "${ICON_DIR}/${sz}x${sz}/apps/pastemesh-desktop.png" 2>/dev/null || true
        fi
    done
    cp -f "${ICON_SRC}/pastemesh.svg" "${ICON_DIR}/scalable/apps/pastemesh.svg" 2>/dev/null || true
    cp -f "${ICON_SRC}/pastemesh.svg" "${ICON_DIR}/scalable/apps/pastemesh-desktop.svg" 2>/dev/null || true
    cp -f "${ICON_SRC}/pastemesh-dark.svg" "${ICON_DIR}/scalable/apps/pastemesh-dark.svg" 2>/dev/null || true
    cp -f "${ICON_SRC}/pastemesh-light.svg" "${ICON_DIR}/scalable/apps/pastemesh-light.svg" 2>/dev/null || true
    cp -f "${ICON_SRC}/pastemesh-symbolic.svg" "${ICON_DIR}/symbolic/apps/pastemesh-symbolic.svg" 2>/dev/null || true
    if command -v gtk-update-icon-cache >/dev/null 2>&1; then
        gtk-update-icon-cache -f -q "${ICON_DIR}" 2>/dev/null || true
    fi
    echo "• Installed desktop icons into ${ICON_DIR}"
fi

# 5b. Automatically register desktop launcher, URI handler, file manager menus & hotkeys on Linux
if [ "$OS" = "linux" ] && [ -x "${INSTALL_BIN}/pastemesh" ]; then
    "${INSTALL_BIN}/pastemesh" config --register-hotkeys --register-desktop 2>/dev/null || true
    echo "• Registered .desktop launcher, pastemesh:// URI handler, and File Explorer context menus"
fi

# 6. Configure systemd user service (if systemd is present and not opted-out)
if [ "$NO_SYSTEMD" -eq 0 ] && command -v systemctl >/dev/null 2>&1; then
    mkdir -p "$SYSTEMD_DIR"
    SERVICE_FILE="$SYSTEMD_DIR/pastemesh.service"

    cat <<'SERVICE_EOF' > "$SERVICE_FILE"
[Unit]
Description=PasteMesh Sovereign Clipboard Daemon
Documentation=https://pastemesh.net
After=network.target

[Service]
Type=simple
ExecStart=%h/.local/bin/pastemesh daemon
Restart=on-failure
RestartSec=3s
Environment=RUST_LOG=info

# Sandboxing & Hardening
ProtectSystem=strict
ProtectHome=false
ReadWritePaths=-%h/.config/pastemesh -%h/.local -%h/.cache /tmp
PrivateTmp=false
NoNewPrivileges=true

[Install]
WantedBy=default.target
SERVICE_EOF

    # If root, adjust ExecStart
    if [ "$(id -u)" -eq 0 ]; then
        sed -i 's|%h/.local/bin/pastemesh|/usr/bin/pastemesh|g' "$SERVICE_FILE" 2>/dev/null || true
    fi

    echo "• Registered systemd service: $SERVICE_FILE"
    systemctl --user daemon-reload 2>/dev/null || true
    echo "  (To start daemon on login: systemctl --user enable --now pastemesh)"
fi

if [ "$OS" = "linux" ] && [ -x "${INSTALL_BIN}/pastemesh" ]; then
    WAS_TRAY=0
    if pgrep -f "^/[^ ]*/pastemesh .*tray" >/dev/null 2>&1; then WAS_TRAY=1; fi
    WAS_STATUS_GUI=0
    if pgrep -f "history_gui\.py.*--status" >/dev/null 2>&1; then WAS_STATUS_GUI=1; fi
    if [ -f "/datadisk/Repos/pastemesh/rust/crates/pastemesh-cli/src/history_gui.py" ]; then
        mkdir -p "$HOME/.config/pastemesh" 2>/dev/null || true
        cp -f "/datadisk/Repos/pastemesh/rust/crates/pastemesh-cli/src/history_gui.py" "$HOME/.config/pastemesh/history_gui.py" 2>/dev/null || true
    fi
    pkill -f "^/[^ ]*/pastemesh .*daemon" 2>/dev/null || true
    pkill -f "^/[^ ]*/pastemesh .*tray" 2>/dev/null || true
    pkill -f "^/[^ ]*/pastemesh-desktop" 2>/dev/null || true
    if [ "$WAS_STATUS_GUI" -eq 1 ]; then
        pkill -f "history_gui\.py.*--status" 2>/dev/null || true
    fi
    sleep 1
    if [ "$NO_SYSTEMD" -eq 0 ] && command -v systemctl >/dev/null 2>&1 && systemctl --user is-enabled pastemesh.service >/dev/null 2>&1; then
        systemctl --user restart pastemesh.service 2>/dev/null || true
    fi
    if ! pgrep -f "^/[^ ]*/pastemesh .*daemon" >/dev/null 2>&1; then
        setsid "${INSTALL_BIN}/pastemesh" daemon --port 5288 </dev/null >/tmp/pastemesh-daemon.log 2>&1 &
        sleep 0.5
    fi
    if [ -x "${INSTALL_BIN}/pastemesh-desktop" ] && ! pgrep -f "^/[^ ]*/pastemesh-desktop" >/dev/null 2>&1; then
        setsid "${INSTALL_BIN}/pastemesh-desktop" --port 5287 --no-browser </dev/null >/tmp/pastemesh-desktop.log 2>&1 &
    fi
    if [ "$WAS_TRAY" -eq 1 ] && ! pgrep -f "^/[^ ]*/pastemesh .*tray" >/dev/null 2>&1; then
        setsid "${INSTALL_BIN}/pastemesh" tray --foreground </dev/null >/tmp/pastemesh-tray.log 2>&1 &
    fi
    if [ "$WAS_STATUS_GUI" -eq 1 ] && [ -f "$HOME/.config/pastemesh/history_gui.py" ]; then
        setsid /usr/bin/python3 "$HOME/.config/pastemesh/history_gui.py" --status --pastemesh-bin "${INSTALL_BIN}/pastemesh" </dev/null >/dev/null 2>&1 &
    fi
    sleep 1
    "${INSTALL_BIN}/pastemesh" update --remote >/dev/null 2>&1 || true
    echo "• Restarted local services and announced v${VERSION} update to mesh peers"
elif [ "$OS" = "darwin" ] && [ "$NO_SYSTEMD" -eq 0 ]; then
    LAUNCH_AGENTS_DIR="$HOME/Library/LaunchAgents"
    mkdir -p "$LAUNCH_AGENTS_DIR" 2>/dev/null || true
    PLIST_FILE="$LAUNCH_AGENTS_DIR/net.pastemesh.desktop.plist"
    cat <<PLIST_EOF > "$PLIST_FILE"
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>net.pastemesh.desktop</string>
    <key>ProgramArguments</key>
    <array>
        <string>${INSTALL_BIN}/pastemesh-desktop</string>
        <string>--no-browser</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
</dict>
</plist>
PLIST_EOF
    echo "• Registered macOS LaunchAgent: $PLIST_FILE"
    echo "  (To start menu bar tray & hotkeys now: launchctl load -w \"$PLIST_FILE\")"
fi

# 7. Check PATH and inform user
PATH_OK=0
case ":${PATH}:" in
    *:"${INSTALL_BIN}":*)
        PATH_OK=1
        ;;
esac

echo ""
echo "=========================================================="
echo "    ✓ PasteMesh v${VERSION} Installed Successfully!       "
echo "=========================================================="
echo "• Binary Location:   $INSTALL_BIN/pastemesh"
echo "• Library Directory: $INSTALL_LIB"
echo "• Default Engine:    $SELECTED_ENGINE"
if [ "$IS_CROSTINI" -eq 1 ]; then
    echo "• Environment:       ChromeOS (Crostini Linux Container)"
    echo "  ✓ ChromeOS Crostini Wayland ('sommelier') clipboard bridge compatibility verified (strictly 2 binaries: pastemesh & pastemesh-desktop)."
fi
echo ""

if [ "$PATH_OK" -eq 0 ]; then
    echo "⚠️  NOTE: '$INSTALL_BIN' is not in your current PATH."
    echo "Add it to your shell configuration by running:"
    echo ""
    echo "  export PATH=\"$INSTALL_BIN:\$PATH\""
    echo ""
    echo "Or add that line to ~/.bashrc or ~/.zshrc."
    echo ""
fi

echo "Quick Start Commands:"
echo "  pastemesh copy \"Hello World\"    # Copy text into sovereign encrypted mesh"
echo "  echo \"data\" | pastemesh          # Quiet copy via standard input"
echo "  pastemesh paste                  # Paste latest clip (bit-exact stdout)"
echo "  pastemesh history                # View encrypted clipboard history"
echo "  pastemesh 3                      # Paste 3rd historical entry"
echo "  pastemesh pair                   # Secure zero-trust peer pairing"
echo "  pastemesh engine get             # Check active engine (desktop/daemon)"
echo ""
echo "Visit https://pastemesh.net for guides, documentation, and source code."
echo ""
