#!/usr/bin/env bash
# Copyright (c) 2025-2026 Cyber Automation Pty Ltd
# Modernize4Linux Binary Verification Script
#
# This script verifies the authenticity and integrity of Modernize4Linux binaries
# before execution. It checks GPG signatures and SHA256 checksums.
#
# Usage:
#   wget https://www.cyberautomation.com.au/Modernize/Linux/VERSION/verify.sh
#   bash verify.sh [binary-name]
#
# Example:
#   bash verify.sh Modernize4Linux-amd64

set -e

VERSION="4.0.3"
BASE_URL="https://www.cyberautomation.com.au/Modernize/Linux/$VERSION"
GPG_KEY_ID="Cyber Automation Pty Ltd"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo "============================================"
echo "Modernize4Linux Binary Verification"
echo "Version: $VERSION"
echo "============================================"
echo ""

# Determine which binary to verify
if [ -z "$1" ]; then
    # Auto-detect architecture
    ARCH=$(uname -m)
    case "$ARCH" in
        x86_64)
            BINARY_NAME="Modernize4Linux-amd64"
            ;;
        aarch64|arm64)
            BINARY_NAME="Modernize4Linux-arm64"
            ;;
        *)
            echo -e "${RED}✗ Error: Unsupported architecture: $ARCH${NC}"
            echo "Please specify binary name: bash verify.sh Modernize4Linux-amd64"
            exit 1
            ;;
    esac
    echo -e "${BLUE}→ Auto-detected architecture: $ARCH${NC}"
    echo -e "${BLUE}→ Verifying binary: $BINARY_NAME${NC}"
else
    BINARY_NAME="$1"
fi

echo ""

# Check if GPG is installed
if ! command -v gpg >/dev/null 2>&1; then
    echo -e "${YELLOW}⚠ Warning: GPG not installed. Cannot verify signatures.${NC}"
    echo "  Install GPG: apt-get install gnupg or yum install gnupg2"
    echo ""
    GPG_AVAILABLE=0
else
    GPG_AVAILABLE=1
fi

# Download binary if not present
if [ ! -f "$BINARY_NAME" ]; then
    echo -e "${BLUE}→ Downloading binary: $BINARY_NAME${NC}"
    wget -q --show-progress "$BASE_URL/$BINARY_NAME" || {
        echo -e "${RED}✗ Failed to download binary${NC}"
        exit 1
    }
    chmod +x "$BINARY_NAME"
fi

# Download signature file
if [ $GPG_AVAILABLE -eq 1 ]; then
    echo -e "${BLUE}→ Downloading GPG signature: ${BINARY_NAME}.asc${NC}"
    wget -q --show-progress "$BASE_URL/${BINARY_NAME}.asc" 2>/dev/null || {
        echo -e "${YELLOW}⚠ Warning: GPG signature not available${NC}"
        GPG_AVAILABLE=0
    }
fi

# Download checksums
echo -e "${BLUE}→ Downloading checksums: SHA256SUMS${NC}"
wget -q --show-progress "$BASE_URL/SHA256SUMS" || {
    echo -e "${RED}✗ Failed to download checksums${NC}"
    exit 1
}

echo ""
echo "============================================"
echo "Verification Steps"
echo "============================================"
echo ""

# Step 1: Verify SHA256 checksum
echo -e "${BLUE}[1/2] Verifying SHA256 checksum...${NC}"
EXPECTED_CHECKSUM=$(grep "$BINARY_NAME" SHA256SUMS | awk '{print $1}')
ACTUAL_CHECKSUM=$(shasum -a 256 "$BINARY_NAME" | awk '{print $1}')

if [ "$EXPECTED_CHECKSUM" = "$ACTUAL_CHECKSUM" ]; then
    echo -e "${GREEN}  ✓ Checksum verified successfully${NC}"
    echo "    Expected: $EXPECTED_CHECKSUM"
    echo "    Actual:   $ACTUAL_CHECKSUM"
else
    echo -e "${RED}  ✗ CHECKSUM MISMATCH - BINARY MAY BE CORRUPTED OR TAMPERED${NC}"
    echo "    Expected: $EXPECTED_CHECKSUM"
    echo "    Actual:   $ACTUAL_CHECKSUM"
    echo ""
    echo -e "${RED}DO NOT RUN THIS BINARY${NC}"
    exit 1
fi

echo ""

# Step 2: Verify GPG signature
if [ $GPG_AVAILABLE -eq 1 ] && [ -f "${BINARY_NAME}.asc" ]; then
    echo -e "${BLUE}[2/2] Verifying GPG signature...${NC}"

    # Import Cyber Automation public key if not already imported
    if ! gpg --list-keys | grep -q "$GPG_KEY_ID" 2>/dev/null; then
        echo -e "${YELLOW}  → Importing Cyber Automation GPG public key...${NC}"
        wget -q "$BASE_URL/GPG-PUBLIC-KEY.asc" -O /tmp/cyberautomation.asc 2>/dev/null || {
            echo -e "${YELLOW}  ⚠ Warning: Could not download GPG public key${NC}"
            echo "    You can manually import the key from the vendor"
            GPG_AVAILABLE=0
        }

        if [ $GPG_AVAILABLE -eq 1 ]; then
            gpg --import /tmp/cyberautomation.asc 2>/dev/null || {
                echo -e "${YELLOW}  ⚠ Warning: Could not import GPG public key${NC}"
                GPG_AVAILABLE=0
            }
            rm -f /tmp/cyberautomation.asc
        fi
    fi

    if [ $GPG_AVAILABLE -eq 1 ]; then
        # Verify the signature
        if gpg --verify "${BINARY_NAME}.asc" "$BINARY_NAME" 2>&1 | grep -q "Good signature"; then
            echo -e "${GREEN}  ✓ GPG signature verified successfully${NC}"
            gpg --verify "${BINARY_NAME}.asc" "$BINARY_NAME" 2>&1 | grep "Good signature" | sed 's/^/    /'
        else
            echo -e "${RED}  ✗ INVALID GPG SIGNATURE - BINARY MAY BE TAMPERED${NC}"
            echo ""
            echo -e "${RED}DO NOT RUN THIS BINARY${NC}"
            exit 1
        fi
    fi
else
    echo -e "${YELLOW}[2/2] GPG signature verification skipped${NC}"
    echo "  Install GPG to enable signature verification"
fi

echo ""
echo "============================================"
echo -e "${GREEN}✓ VERIFICATION COMPLETE${NC}"
echo "============================================"
echo ""
echo "The binary has passed all available verification checks."
echo "You can now safely run: ./$BINARY_NAME"
echo ""
echo "Security recommendations:"
echo "  • Always verify binaries before first use"
echo "  • Run with appropriate privileges (usually root)"
echo "  • Review logs after migration completes"
echo "  • Keep backup of original system before migration"
echo ""
echo "For support, contact: support@cyberautomation.com.au"
echo "============================================"
