#!/bin/bash
# PiDOC Client Quick Install Script (Global Edition)

set -e

DEBUG=0
CLI_KEY=""  # Key passed via command-line argument

# Parse arguments
for arg in "$@"; do
    case "$arg" in
        --debug|-d) DEBUG=1; set -x ;;
        *) CLI_KEY="$arg" ;;  # Non-option argument as key
    esac
done

BASE_URL="https://dl.piops.net/pidoc"
OPS_URL="https://ops.piops.net"
PRODUCT_NAME="Pi Device Operations Connector"
APP_NAME="pidoc"
PIDOC_GROUP="pidoc"

run_root() {
    if [ "$EUID" -ne 0 ]; then
        sudo "$@"
    else
        "$@"
    fi
}

setup_pidoc_group() {
    echo "Configuring ${PIDOC_GROUP} user group..."

    if ! getent group "${PIDOC_GROUP}" >/dev/null 2>&1; then
        if ! run_root groupadd --system "${PIDOC_GROUP}" 2>/dev/null; then
            run_root groupadd "${PIDOC_GROUP}"
        fi
        echo "✓ Created ${PIDOC_GROUP} group"
    else
        echo "✓ ${PIDOC_GROUP} group already exists"
    fi

    TARGET_USER="${SUDO_USER:-${USER:-}}"
    if [ -z "$TARGET_USER" ] && command -v logname >/dev/null 2>&1; then
        TARGET_USER=$(logname 2>/dev/null || true)
    fi

    if [ -n "$TARGET_USER" ] && [ "$TARGET_USER" != "root" ] && id "$TARGET_USER" >/dev/null 2>&1; then
        run_root usermod -aG "${PIDOC_GROUP}" "$TARGET_USER"
        echo "✓ Added user ${TARGET_USER} to ${PIDOC_GROUP} group"
        echo "  Note: group membership changes take effect after re-login"
    else
        echo "Note: no regular user detected for group membership update, skipping"
    fi
}

echo "========================================="
echo "${PRODUCT_NAME} Quick Install Script"
echo "========================================="
echo ""

# Allow specifying version via PIDOC_VERSION environment variable
if [ -n "$PIDOC_VERSION" ]; then
    VERSION="$PIDOC_VERSION"
    echo "Using specified version: ${VERSION}"
    echo ""
else
    # Get latest version
    echo "Checking for latest version..."
    if command -v curl &> /dev/null; then
        LATEST_VERSION=$(curl -s "${BASE_URL}/latest.txt" 2>/dev/null || echo "")
    elif command -v wget &> /dev/null; then
        LATEST_VERSION=$(wget -qO- "${BASE_URL}/latest.txt" 2>/dev/null || echo "")
    else
        echo "Error: Neither wget nor curl found. Please install one of them first."
        exit 1
    fi

    # Validate version format (should be x.y.z or x.y.z-xxx)
    if [ -z "$LATEST_VERSION" ] || ! echo "$LATEST_VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+'; then
        echo "Error: Unable to retrieve a valid version"
        if [ $DEBUG -eq 1 ] && [ -n "$LATEST_VERSION" ]; then
            echo "Debug info: received content:"
            echo "$LATEST_VERSION" | head -n 5
        fi
        echo "Please check your network connection and try again later."
        exit 1
    fi
    
    echo "Latest version: ${LATEST_VERSION}"
    VERSION="$LATEST_VERSION"
    echo ""
fi

    # Detect architecture
if command -v dpkg &> /dev/null; then
    ARCH=$(dpkg --print-architecture)
else
    MACHINE=$(uname -m)
    case "$MACHINE" in
        x86_64)
            ARCH="amd64"
            ;;
        i386|i686)
            ARCH="i386"
            ;;
        aarch64)
            ARCH="arm64"
            ;;
        armv7l|armv6l)
            ARCH="armhf"
            ;;
        loongarch64)
            # Will be resolved to loong64 or loongarch64 based on kernel version below
            ;;
        riscv64)
            ARCH="riscv64"
            ;;
        *)
            echo "Error: Unsupported architecture '$MACHINE'"
            echo "Supported architectures: amd64, i386, arm64, armhf, loongarch64, riscv64"
            exit 1
            ;;
    esac
fi

# LoongArch: choose ABI1.0 or ABI2.0 package based on kernel version
# - kernel >= 5.19: loong64 (ABI2.0)
# - kernel < 5.19: loongarch64 (ABI1.0, old Loongnix)
case "$ARCH" in
    loongarch64)
        KERNEL_MAJOR=$(uname -r | cut -d. -f1)
        KERNEL_MINOR=$(uname -r | cut -d. -f2)
        if [ "$KERNEL_MAJOR" -gt 5 ] || { [ "$KERNEL_MAJOR" -eq 5 ] && [ "$KERNEL_MINOR" -ge 19 ]; }; then
            ARCH="loong64"
        else
            ARCH="loongarch64"
        fi
        ;;
esac

echo "Detected architecture: $ARCH"
DEB_FILE="${APP_NAME}_${VERSION}_${ARCH}.deb"
DOWNLOAD_URL="${BASE_URL}/${DEB_FILE}"

echo "Download URL: $DOWNLOAD_URL"
echo ""

# Check if already installed
IS_UPGRADE=0
if command -v ${APP_NAME} &> /dev/null; then
    INSTALLED_VERSION=$(${APP_NAME} version 2>&1 | grep -oP 'v\K[0-9.]+' || echo "unknown")
    echo "Installed version detected: v${INSTALLED_VERSION}"
    
    if [ "$INSTALLED_VERSION" = "$VERSION" ]; then
        echo "Already up to date (v${VERSION}). Skipping download."
        exit 0
    else
        echo "Upgrading from v${INSTALLED_VERSION} to v${VERSION}"
        IS_UPGRADE=1
    fi
    echo ""
fi

# Download
echo "Downloading ${DEB_FILE}..."
echo "URL: ${DOWNLOAD_URL}"
TEMP_DIR=$(mktemp -d)
chmod 755 "$TEMP_DIR"
cd "$TEMP_DIR"

if command -v wget &> /dev/null; then
    if ! wget -q --show-progress "$DOWNLOAD_URL"; then
        echo ""
        echo "Error: Download failed"
        echo "URL: ${DOWNLOAD_URL}"
        echo "Please check:"
        echo "  1. Your network connection"
        echo "  2. Whether the file exists on the server"
        echo "  3. Try visiting manually: ${DOWNLOAD_URL}"
        rm -rf "$TEMP_DIR"
        exit 1
    fi
elif command -v curl &> /dev/null; then
    if ! curl -f -L -O "$DOWNLOAD_URL"; then
        echo ""
        echo "Error: Download failed"
        echo "URL: ${DOWNLOAD_URL}"
        echo "Please check:"
        echo "  1. Your network connection"
        echo "  2. Whether the file exists on the server"
        echo "  3. Try visiting manually: ${DOWNLOAD_URL}"
        rm -rf "$TEMP_DIR"
        exit 1
    fi
else
    echo "Error: Neither wget nor curl found. Please install one of them first."
    rm -rf "$TEMP_DIR"
    exit 1
fi

echo "✓ Download complete"
echo ""

# Install
echo "Installing..."
if [ "$EUID" -ne 0 ]; then
    echo "Root privileges required for installation"
    sudo apt install -y "./${DEB_FILE}" || {
        echo "Error: Installation failed"
        rm -rf "$TEMP_DIR"
        exit 1
    }
else
    apt install -y "./${DEB_FILE}" || {
        echo "Error: Installation failed"
        rm -rf "$TEMP_DIR"
        exit 1
    }
fi

setup_pidoc_group

# ── Service Installation ────────────────────────
# Check if service is already running
SERVICE_ACTIVE=$(systemctl is-active pidoc 2>/dev/null || echo "unknown")
if [ "$SERVICE_ACTIVE" = "active" ]; then
    echo "✓ Service is already running, skipping service installation"
else
    # Check if a key is already configured
    HAS_KEY=0
    if [ -f "/etc/pidoc/config.json" ]; then
        EXISTING_KEY=$(grep -oP '"private_key"\s*:\s*"\K[^"]+' /etc/pidoc/config.json 2>/dev/null || echo "")
        if [ -n "$EXISTING_KEY" ]; then
            HAS_KEY=1
            echo "✓ Existing key configuration detected"
        fi
    fi

    if [ "$HAS_KEY" -eq 1 ]; then
        # Key exists: install without key argument (use config key)
        echo ""
        echo "Installing system service..."
        if run_root ${APP_NAME} service install; then
            echo "Starting service..."
            run_root systemctl start pidoc
        else
            echo "⚠ Service installation failed (SSH health check may have failed), but the software is installed"
            echo "  You can run later: sudo pidoc service install"
        fi
    else
        # No key configured: use CLI arg or PIDOC_KEY env var first, otherwise prompt
        KEY_ARG="${CLI_KEY:-${PIDOC_KEY:-}}"
        if [ -z "$KEY_ARG" ]; then
            echo ""
            echo "┌─────────────────────────────────────────────┐"
            echo "│  PiDOC Key Required                        │"
            echo "│  Visit ${OPS_URL} to get your key │"
            echo "│  Pass via: curl ... | bash -s -- <key>      │"
            echo "└─────────────────────────────────────────────┘"
            echo ""
            while [ -z "$KEY_ARG" ]; do
                read -p "Enter your key (leave blank to skip service install): " KEY_ARG
                if [ -z "$KEY_ARG" ]; then
                    echo "Hint: Skip service install. You can run later: sudo pidoc service install <key>"
                    break
                fi
            done
        fi

        if [ -n "$KEY_ARG" ]; then
            echo ""
            echo "Installing system service..."
            if run_root ${APP_NAME} service install "$KEY_ARG"; then
                echo "Starting service..."
                run_root systemctl start pidoc
            else
                echo "⚠ Service installation failed (SSH health check may have failed), but the software is installed"
                echo "  You can run later: sudo pidoc service install <key>"
            fi
        else
            echo ""
            echo "Skipping service installation"
        fi
    fi
fi

# Cleanup
cd /
rm -rf "$TEMP_DIR"

echo ""
echo "========================================="
echo "${APP_NAME} Installation complete!"
echo "========================================="
echo ""
echo "Available commands:"
echo "  Install service:  sudo pidoc service install <key>"
echo "  Check status:     sudo pidoc service status"
echo "  Run in terminal:  pidoc run -k <key>"
echo "  Full check:        sudo pidoc check"
echo "========================================="
if [ "$SERVICE_ACTIVE" != "active" ] && [ "$HAS_KEY" -eq 0 ]; then
    echo "Get your key at: ${OPS_URL}"
    echo "========================================="
fi
