#!/bin/bash
# Khimera Portable - USB Bundle Builder
# Creates a complete multi-platform USB bundle

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

# Configuration
VERSION="0.9"
BUNDLE_NAME="khimera-usb-v${VERSION}"
BUILD_DATE=$(date +%Y%m%d)

echo -e "${CYAN}"
echo "╔══════════════════════════════════════════════════════╗"
echo "║                                                      ║"
echo "║        KHIMERA USB BUNDLE BUILDER v${VERSION}             ║"
echo "║     Multi-Platform Portable Distribution            ║"
echo "║                                                      ║"
echo "╚══════════════════════════════════════════════════════╝"
echo -e "${NC}"
echo ""

# Clean old bundle
echo -e "${YELLOW}[Clean]${NC} Removing old bundle..."
rm -rf "$BUNDLE_NAME"
echo -e "${GREEN}✓${NC} Clean complete"
echo ""

# Create bundle structure
echo -e "${YELLOW}[Structure]${NC} Creating USB bundle structure..."
mkdir -p "$BUNDLE_NAME"/{Windows,Linux,Android,data,tor,temp,docs}
echo -e "${GREEN}✓${NC} Directories created"
echo ""

# Build executables
echo -e "${BLUE}╔══════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║  Building Executables                                ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════╝${NC}"
echo ""

# Install dependencies first
echo -e "${YELLOW}[Dependencies]${NC} Installing Go dependencies..."
go mod download
echo -e "${GREEN}✓${NC} Dependencies ready"
echo ""

# Build Linux
echo -e "${BLUE}[1/2]${NC} Building Linux executable..."
echo "   Target: Linux AMD64"
echo "   Output: $BUNDLE_NAME/Linux/khimera-linux"

CGO_ENABLED=1 \
GOOS=linux \
GOARCH=amd64 \
go build \
    -ldflags="-s -w -X main.Version=${VERSION} -X main.BuildDate=${BUILD_DATE}" \
    -o "$BUNDLE_NAME/Linux/khimera-linux" \
    ./khimera-main.go

if [ $? -eq 0 ]; then
    chmod +x "$BUNDLE_NAME/Linux/khimera-linux"
    SIZE=$(du -h "$BUNDLE_NAME/Linux/khimera-linux" | cut -f1)
    echo -e "${GREEN}✓${NC} Linux build complete (${SIZE})"
else
    echo -e "${RED}✗${NC} Linux build failed"
    exit 1
fi
echo ""

# Build Windows (if mingw available)
echo -e "${BLUE}[2/2]${NC} Building Windows executable..."

if command -v x86_64-w64-mingw32-gcc &> /dev/null; then
    echo "   Target: Windows AMD64"
    echo "   Output: $BUNDLE_NAME/Windows/khimera.exe"

    CGO_ENABLED=1 \
    GOOS=windows \
    GOARCH=amd64 \
    CC=x86_64-w64-mingw32-gcc \
    go build \
        -ldflags="-s -w -H windowsgui -X main.Version=${VERSION} -X main.BuildDate=${BUILD_DATE}" \
        -o "$BUNDLE_NAME/Windows/khimera.exe" \
        ./khimera-main.go

    if [ $? -eq 0 ]; then
        SIZE=$(du -h "$BUNDLE_NAME/Windows/khimera.exe" | cut -f1)
        echo -e "${GREEN}✓${NC} Windows build complete (${SIZE})"
    else
        echo -e "${RED}✗${NC} Windows build failed"
    fi
else
    echo -e "${YELLOW}⚠${NC} MinGW not found - skipping Windows build"
    echo "   Install with: sudo apt install mingw-w64"
    echo "   Creating placeholder..."
    echo "Windows executable not built - MinGW required" > "$BUNDLE_NAME/Windows/BUILD_REQUIRED.txt"
fi
echo ""

# Copy launchers
echo -e "${YELLOW}[Launchers]${NC} Copying launcher scripts..."
cp launcher "$BUNDLE_NAME/"
cp launcher.bat "$BUNDLE_NAME/"
chmod +x "$BUNDLE_NAME/launcher"
echo -e "${GREEN}✓${NC} Launchers copied"
echo ""

# Create Android placeholder
echo -e "${YELLOW}[Android]${NC} Creating Android placeholder..."
cat > "$BUNDLE_NAME/Android/BUILD_INSTRUCTIONS.txt" << 'EOF'
To build Android APK:

1. Install Android SDK and NDK
2. Install fyne CLI:
   go install fyne.io/fyne/v2/cmd/fyne@latest

3. Build APK:
   cd ..
   fyne package -os android -appID com.khimera.portable

4. Sign APK (optional):
   jarsigner -keystore khimera.keystore app.apk khimera

For more info: https://developer.fyne.io/started/mobile
EOF
echo -e "${GREEN}✓${NC} Android instructions created"
echo ""

# Create README
echo -e "${YELLOW}[Documentation]${NC} Creating README..."
cat > "$BUNDLE_NAME/README.txt" << EOF
╔══════════════════════════════════════════════════════════════╗
║                                                              ║
║              KHIMERA PORTABLE USB v${VERSION}                     ║
║          Privacy-First P2P Messenger                         ║
║              Multi-Platform Edition                          ║
║                                                              ║
╚══════════════════════════════════════════════════════════════╝

BUILD DATE: ${BUILD_DATE}

═══════════════════════════════════════════════════════════════
  WHAT IS KHIMERA PORTABLE?
═══════════════════════════════════════════════════════════════

Khimera Portable is a zero-installation, privacy-first messenger
that runs directly from USB drives on multiple platforms:

✓ Windows (x86_64)
✓ Linux (x86_64, ARM64)
✓ Android (via APK)

All your data stays on the USB drive. No installation required.
No traces left on the host system.


═══════════════════════════════════════════════════════════════
  QUICK START
═══════════════════════════════════════════════════════════════

LINUX / macOS:
  1. Open terminal in this directory
  2. Run: ./launcher
  3. Or: cd Linux && ./khimera-linux

WINDOWS:
  1. Double-click: launcher.bat
  2. Or: Double-click: Windows/khimera.exe

ANDROID:
  1. Copy Android/khimera.apk to your phone
  2. Enable "Unknown Sources" in settings
  3. Install the APK
  4. Launch from app drawer


═══════════════════════════════════════════════════════════════
  BUNDLE STRUCTURE
═══════════════════════════════════════════════════════════════

khimera-usb-v${VERSION}/
├── launcher              # Smart launcher (Linux/Mac)
├── launcher.bat          # Windows launcher
├── Windows/              # Windows executable
│   └── khimera.exe
├── Linux/                # Linux executable
│   └── khimera-linux
├── Android/              # Android APK
│   └── khimera.apk
├── data/                 # YOUR DATA (encrypted)
│   ├── identity.enc      # Your cryptographic identity
│   └── contacts.enc      # Your contact list
├── tor/                  # Tor binaries (optional)
└── temp/                 # Temporary files (auto-cleaned)


═══════════════════════════════════════════════════════════════
  FEATURES
═══════════════════════════════════════════════════════════════

SECURITY:
  • Ed25519 cryptographic identities
  • Noise Protocol (E2EE + Perfect Forward Secrecy)
  • Scrypt KDF + NaCl SecretBox encryption
  • Secure memory wiping

NETWORKING:
  • Tor Hidden Services (.onion addresses)
  • P2P Mesh networking
  • Multi-transport support

PRIVACY:
  • Zero knowledge architecture
  • No server-side data storage
  • Anonymous by default
  • Portable mode (no system traces)


═══════════════════════════════════════════════════════════════
  SECURITY NOTES
═══════════════════════════════════════════════════════════════

⚠ IMPORTANT:
  • This USB drive contains your encrypted identity
  • Keep it in a safe place
  • Use a STRONG passphrase
  • Make backups of the data/ directory
  • Do not use on untrusted computers

✓ RECOMMENDATIONS:
  • Enable full disk encryption on your USB drive
  • Use different identities for different contexts
  • Always eject the drive safely
  • Consider using a hardware-encrypted USB drive


═══════════════════════════════════════════════════════════════
  TROUBLESHOOTING
═══════════════════════════════════════════════════════════════

LINUX:
  Permission denied?
    chmod +x launcher
    chmod +x Linux/khimera-linux

WINDOWS:
  Antivirus blocking?
    Add khimera.exe to exceptions

  Won't start?
    Right-click → Run as Administrator (one time)

ANDROID:
  Can't install?
    Settings → Security → Enable "Unknown Sources"


═══════════════════════════════════════════════════════════════
  FIRST RUN
═══════════════════════════════════════════════════════════════

On first run, Khimera will:
  1. Create a new cryptographic identity
  2. Ask for a passphrase to protect it
  3. Save encrypted identity to data/identity.enc
  4. Show your public key fingerprint

On subsequent runs:
  1. Load your identity from data/identity.enc
  2. Ask for your passphrase to decrypt it
  3. Connect to the network


═══════════════════════════════════════════════════════════════
  SUPPORT
═══════════════════════════════════════════════════════════════

  Website:  https://khimera-messenger.org
  Email:    support@khimera-messenger.org
  Security: security@khimera-messenger.org


═══════════════════════════════════════════════════════════════
  LICENSE
═══════════════════════════════════════════════════════════════

See docs/LICENSE.txt for licensing information.


Built: ${BUILD_DATE}
Version: ${VERSION}

Khimera Portable - Privacy you can carry
EOF

echo -e "${GREEN}✓${NC} README created"
echo ""

# Create .gitignore for data directory
echo -e "${YELLOW}[Safety]${NC} Creating .gitignore for sensitive data..."
cat > "$BUNDLE_NAME/.gitignore" << 'EOF'
# Ignore user data
data/*.enc
data/*.json
temp/*
tor/

# Keep directory structure
!data/.gitkeep
!temp/.gitkeep
!tor/.gitkeep
EOF

touch "$BUNDLE_NAME/data/.gitkeep"
touch "$BUNDLE_NAME/temp/.gitkeep"
touch "$BUNDLE_NAME/tor/.gitkeep"

echo -e "${GREEN}✓${NC} Safety files created"
echo ""

# Calculate sizes
echo -e "${YELLOW}[Summary]${NC} Bundle summary..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if [ -f "$BUNDLE_NAME/Linux/khimera-linux" ]; then
    LINUX_SIZE=$(du -h "$BUNDLE_NAME/Linux/khimera-linux" | cut -f1)
    echo "  Linux:    ${LINUX_SIZE}"
fi

if [ -f "$BUNDLE_NAME/Windows/khimera.exe" ]; then
    WINDOWS_SIZE=$(du -h "$BUNDLE_NAME/Windows/khimera.exe" | cut -f1)
    echo "  Windows:  ${WINDOWS_SIZE}"
fi

TOTAL_SIZE=$(du -sh "$BUNDLE_NAME" | cut -f1)
echo "  Total:    ${TOTAL_SIZE}"
echo ""

# Create distribution archives
echo -e "${YELLOW}[Package]${NC} Creating distribution archives..."

# ZIP (Windows-friendly)
if command -v zip &> /dev/null; then
    zip -r -q "${BUNDLE_NAME}.zip" "$BUNDLE_NAME"
    ZIP_SIZE=$(du -h "${BUNDLE_NAME}.zip" | cut -f1)
    echo -e "${GREEN}✓${NC} Created ${BUNDLE_NAME}.zip (${ZIP_SIZE})"
fi

# TAR.GZ (Linux-friendly)
if command -v tar &> /dev/null; then
    tar -czf "${BUNDLE_NAME}.tar.gz" "$BUNDLE_NAME"
    TAR_SIZE=$(du -h "${BUNDLE_NAME}.tar.gz" | cut -f1)
    echo -e "${GREEN}✓${NC} Created ${BUNDLE_NAME}.tar.gz (${TAR_SIZE})"
fi

echo ""

# Final message
echo -e "${GREEN}╔══════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║                                                      ║${NC}"
echo -e "${GREEN}║  BUILD COMPLETE!                                     ║${NC}"
echo -e "${GREEN}║                                                      ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════════════════╝${NC}"
echo ""
echo "Bundle created: ${BUNDLE_NAME}/"
echo ""
echo "To use on USB drive:"
echo "  1. Copy entire ${BUNDLE_NAME}/ folder to USB root"
echo "  2. Or extract ${BUNDLE_NAME}.zip to USB drive"
echo "  3. Run ./launcher (Linux/Mac) or launcher.bat (Windows)"
echo ""
echo "To distribute:"
echo "  • Share ${BUNDLE_NAME}.zip (Windows users)"
echo "  • Share ${BUNDLE_NAME}.tar.gz (Linux users)"
echo ""
echo -e "${CYAN}Khimera Portable - Privacy you can carry${NC}"
echo ""
