#!/bin/bash
# ============================================================================
#  Positronic Node — Linux Installer
#  Run this script to install the Positronic validator node.
#
#  Usage:
#    chmod +x Positronic-Installer.sh
#    ./Positronic-Installer.sh
#
#  What this does:
#    1. Downloads the latest Positronic binary from positronic-ai.network
#    2. Verifies SHA-512 integrity checksum
#    3. Installs to ~/.local/bin/ (no sudo required)
#    4. Creates desktop menu entry
#    5. Launches Positronic Node
#
#  No source code is downloaded — only the compiled, encrypted binary.
# ============================================================================

set -euo pipefail

VERSION="0.1.0"
BASE_URL="https://positronic-ai.network/download"
ARCH="$(uname -m)"
ARCHIVE_FILE="Positronic-v${VERSION}-linux-${ARCH}.tar.gz"
ARCHIVE_URL="${BASE_URL}/${ARCHIVE_FILE}"
SHA_URL="${BASE_URL}/${ARCHIVE_FILE}.sha512"
INSTALL_DIR="$HOME/.local/bin"
DATA_DIR="$HOME/.positronic"
ICONS_DIR="$HOME/.local/share/icons"
APPS_DIR="$HOME/.local/share/applications"
TMP_DIR=$(mktemp -d)

# Colors
C='\033[0;36m' G='\033[0;32m' R='\033[0;31m' Y='\033[1;33m' B='\033[1;34m' P='\033[0;35m' NC='\033[0m'

cleanup() { rm -rf "$TMP_DIR"; }
trap cleanup EXIT

clear
echo ""
echo -e "${P}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${P}║                                                              ║${NC}"
echo -e "${P}║      ⚡  Positronic Node — Linux Installer  ⚡               ║${NC}"
echo -e "${P}║                                                              ║${NC}"
echo -e "${P}║      AI-Validated Layer-1 Blockchain                         ║${NC}"
echo -e "${P}║      Version: ${VERSION}                                           ║${NC}"
echo -e "${P}║                                                              ║${NC}"
echo -e "${P}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""

# ── Check Linux ──────────────────────────────────────────────────────
if [[ "$(uname)" != "Linux" ]]; then
    echo -e "${R}  ✗ This installer is for Linux only.${NC}"
    echo "  For Windows, download Positronic.exe from positronic-ai.network/download"
    echo "  For macOS, download Positronic-Installer.command"
    read -p "Press Enter to exit..."
    exit 1
fi

# Architecture check
if [[ "$ARCH" != "x86_64" && "$ARCH" != "aarch64" ]]; then
    echo -e "${R}  ✗ Unsupported architecture: $ARCH${NC}"
    echo "  Positronic supports x86_64 (amd64) and aarch64 (arm64)"
    read -p "Press Enter to exit..."
    exit 1
fi

DISTRO=$(lsb_release -d 2>/dev/null | cut -f2 || cat /etc/os-release 2>/dev/null | grep PRETTY_NAME | cut -d= -f2 | tr -d '"' || echo "Linux")
KERNEL=$(uname -r)
echo -e "${B}[1/6]${NC} $DISTRO detected ($ARCH, kernel $KERNEL)"

# ── Check if already installed ───────────────────────────────────────
if [[ -f "$INSTALL_DIR/Positronic" ]]; then
    echo -e "${Y}  ⚠ Positronic already installed at $INSTALL_DIR/Positronic${NC}"
    read -p "  Overwrite? (y/N): " CONFIRM
    if [[ "${CONFIRM,,}" != "y" ]]; then
        echo "  Cancelled. Launching existing installation..."
        "$INSTALL_DIR/Positronic" &
        disown
        exit 0
    fi
fi

# ── Download archive ─────────────────────────────────────────────────
echo -e "\n${B}[2/6]${NC} Downloading Positronic Node..."
echo "  URL: $ARCHIVE_URL"

ARCHIVE_PATH="$TMP_DIR/$ARCHIVE_FILE"

if ! curl -fSL --progress-bar -o "$ARCHIVE_PATH" "$ARCHIVE_URL" 2>&1; then
    echo ""
    echo -e "${R}  ✗ Download failed.${NC}"
    echo ""
    echo -e "  The Linux version for $ARCH may not be available yet."
    echo -e "  Check ${C}https://positronic-ai.network/download${NC} for updates."
    echo ""
    read -p "Press Enter to exit..."
    exit 1
fi

ARCHIVE_SIZE=$(du -m "$ARCHIVE_PATH" | awk '{print $1}')
echo -e "  ${G}✓${NC} Downloaded ($ARCHIVE_SIZE MB)"

# ── Verify integrity ─────────────────────────────────────────────────
echo -e "\n${B}[3/6]${NC} Verifying SHA-512 checksum..."

SHA_PATH="$TMP_DIR/checksum.sha512"
if curl -fsSL -o "$SHA_PATH" "$SHA_URL" 2>/dev/null; then
    EXPECTED=$(awk '{print $1}' "$SHA_PATH")
    ACTUAL=$(sha512sum "$ARCHIVE_PATH" | awk '{print $1}')

    if [[ "$EXPECTED" == "$ACTUAL" ]]; then
        echo -e "  ${G}✓${NC} Checksum verified — file is authentic"
    else
        echo -e "${R}  ✗ CHECKSUM MISMATCH — file may be corrupted or tampered!${NC}"
        echo "  Expected: ${EXPECTED:0:32}..."
        echo "  Got:      ${ACTUAL:0:32}..."
        echo ""
        read -p "  Continue anyway? (y/N): " CONFIRM
        if [[ "${CONFIRM,,}" != "y" ]]; then
            exit 1
        fi
    fi
else
    echo -e "  ${Y}⚠${NC} Could not download checksum — skipping verification"
fi

# ── Install ──────────────────────────────────────────────────────────
echo -e "\n${B}[4/6]${NC} Installing to $INSTALL_DIR..."

# Create directories
mkdir -p "$INSTALL_DIR"
mkdir -p "$DATA_DIR"
mkdir -p "$ICONS_DIR"
mkdir -p "$APPS_DIR"

# Extract archive
EXTRACT_DIR="$TMP_DIR/extract"
mkdir -p "$EXTRACT_DIR"
tar -xzf "$ARCHIVE_PATH" -C "$EXTRACT_DIR"

# Find the binary inside extracted directory
EXTRACTED_BIN=$(find "$EXTRACT_DIR" -name "Positronic" -type f | head -1)
EXTRACTED_ICON=$(find "$EXTRACT_DIR" -name "positronic.png" -type f | head -1)
EXTRACTED_DESKTOP=$(find "$EXTRACT_DIR" -name "positronic.desktop" -type f | head -1)

if [[ -z "$EXTRACTED_BIN" ]]; then
    echo -e "${R}  ✗ Positronic binary not found in archive${NC}"
    read -p "Press Enter to exit..."
    exit 1
fi

# Copy binary
cp "$EXTRACTED_BIN" "$INSTALL_DIR/Positronic"
chmod +x "$INSTALL_DIR/Positronic"
echo -e "  ${G}✓${NC} Binary installed: $INSTALL_DIR/Positronic"

# Copy icon if exists
if [[ -n "$EXTRACTED_ICON" ]]; then
    cp "$EXTRACTED_ICON" "$ICONS_DIR/positronic.png"
    echo -e "  ${G}✓${NC} Icon installed: $ICONS_DIR/positronic.png"
fi

# ── Desktop entry ────────────────────────────────────────────────────
echo -e "\n${B}[5/6]${NC} Creating desktop menu entry..."

# Create .desktop file with correct paths
cat > "$APPS_DIR/positronic.desktop" << DESKTOP_EOF
[Desktop Entry]
Name=Positronic Node
Comment=AI-Validated Blockchain Validator Node
Exec=$INSTALL_DIR/Positronic
Icon=$ICONS_DIR/positronic.png
Terminal=false
Type=Application
Categories=Finance;Network;
Keywords=blockchain;validator;crypto;node;
StartupWMClass=positronic
DESKTOP_EOF

chmod +x "$APPS_DIR/positronic.desktop"

# Update desktop database if available
if command -v update-desktop-database &>/dev/null; then
    update-desktop-database "$APPS_DIR" 2>/dev/null || true
fi

echo -e "  ${G}✓${NC} Desktop entry created"
echo -e "  ${G}✓${NC} Positronic will appear in your application menu"

# ── Ensure ~/.local/bin is in PATH ───────────────────────────────────
if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
    echo ""
    echo -e "  ${Y}⚠${NC} $INSTALL_DIR is not in your PATH"
    echo -e "  Add this to your ${C}~/.bashrc${NC} or ${C}~/.zshrc${NC}:"
    echo -e "    ${C}export PATH=\"\$HOME/.local/bin:\$PATH\"${NC}"
fi

# ── Launch ───────────────────────────────────────────────────────────
echo -e "\n${B}[6/6]${NC} Launching Positronic Node..."
echo ""
echo -e "${G}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${G}║                                                              ║${NC}"
echo -e "${G}║         ✓  Installation Complete!                            ║${NC}"
echo -e "${G}║                                                              ║${NC}"
echo -e "${G}║  Positronic Node is installed at:                            ║${NC}"
echo -e "${G}║    $INSTALL_DIR/Positronic                                   ║${NC}"
echo -e "${G}║                                                              ║${NC}"
echo -e "${G}║  Data directory:                                             ║${NC}"
echo -e "${G}║    ~/.positronic/                                            ║${NC}"
echo -e "${G}║                                                              ║${NC}"
echo -e "${G}║  To uninstall:                                               ║${NC}"
echo -e "${G}║    rm ~/.local/bin/Positronic                                ║${NC}"
echo -e "${G}║    rm ~/.local/share/applications/positronic.desktop         ║${NC}"
echo -e "${G}║                                                              ║${NC}"
echo -e "${G}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""

# Launch in background
"$INSTALL_DIR/Positronic" &
disown

echo "You can close this terminal window."
