#!/bin/bash

# Build script for backup-tui
# Ensures consistent binary naming across build sessions

set -e

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

# Configuration
BINARY_NAME="backup-tui"
SOURCE_FILE="main.go"
TUI_DIR="/home/acedanger/shell/tui"
SHELL_DIR="/home/acedanger/shell"

# Print colored output
print_color() {
    local color="$1"
    local message="$2"
    case "$color" in
        "green")  printf "${GREEN}%s${NC}\n" "$message" ;;
        "yellow") printf "${YELLOW}%s${NC}\n" "$message" ;;
        "red")    printf "${RED}%s${NC}\n" "$message" ;;
        *)        printf "%s\n" "$message" ;;
    esac
}

print_color "yellow" "🔨 Building Backup TUI..."

# Change to TUI directory
cd "$TUI_DIR"

# Check if Go is available
if ! command -v go &> /dev/null; then
    print_color "red" "❌ Go is not installed or not in PATH"
    print_color "yellow" "Please install Go 1.19+ or set up the Go environment"
    exit 1
fi

# Ensure dependencies are available
print_color "yellow" "📦 Checking Go dependencies..."
if ! go mod tidy; then
    print_color "red" "❌ Failed to download Go dependencies"
    exit 1
fi

# Build the binary with consistent naming
print_color "yellow" "🔧 Building ${BINARY_NAME}..."
if go build -o "$BINARY_NAME" "$SOURCE_FILE"; then
    print_color "green" "✅ Successfully built ${BINARY_NAME}"
else
    print_color "red" "❌ Build failed"
    exit 1
fi

# Copy to shell directory for easy access
if cp "$BINARY_NAME" "$SHELL_DIR/$BINARY_NAME"; then
    print_color "green" "✅ Copied binary to shell directory"
else
    print_color "yellow" "⚠️ Could not copy to shell directory"
fi

# Make executable
chmod +x "$BINARY_NAME"
chmod +x "$SHELL_DIR/$BINARY_NAME" 2>/dev/null || true

print_color "green" "🎉 Build completed successfully!"
print_color "yellow" "Binary location: $TUI_DIR/$BINARY_NAME"
print_color "yellow" "Also available: $SHELL_DIR/$BINARY_NAME"
print_color "yellow" "Launch with: ./backup-tui"
