#!/bin/bash
set -e

# Build script for creating Debian package

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
BUILD_DIR="$PROJECT_DIR/build"
DEB_DIR="$PROJECT_DIR/debian"

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

echo_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

echo_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

echo_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Clean previous builds
echo_info "Cleaning previous builds..."
rm -rf "$BUILD_DIR"
mkdir -p "$BUILD_DIR"

# Change to project directory
cd "$PROJECT_DIR"

# Build the application
echo_info "Building SkyView application..."
export CGO_ENABLED=0
export GOOS=linux
export GOARCH=amd64

go build -ldflags="-w -s -X main.version=$(git describe --tags --always --dirty)" \
    -o "$DEB_DIR/usr/bin/skyview" \
    ./cmd/skyview

if [ $? -ne 0 ]; then
    echo_error "Failed to build application"
    exit 1
fi

echo_info "Built binary: $(file "$DEB_DIR/usr/bin/skyview")"

# Set executable permission
chmod +x "$DEB_DIR/usr/bin/skyview"

# Get package info
VERSION=$(grep "Version:" "$DEB_DIR/DEBIAN/control" | cut -d' ' -f2)
PACKAGE=$(grep "Package:" "$DEB_DIR/DEBIAN/control" | cut -d' ' -f2)
ARCH=$(grep "Architecture:" "$DEB_DIR/DEBIAN/control" | cut -d' ' -f2)

DEB_FILE="${PACKAGE}_${VERSION}_${ARCH}.deb"

echo_info "Creating Debian package: $DEB_FILE"

# Calculate installed size
INSTALLED_SIZE=$(du -sk "$DEB_DIR" | cut -f1)
sed -i "s/Installed-Size:.*/Installed-Size: $INSTALLED_SIZE/" "$DEB_DIR/DEBIAN/control" 2>/dev/null || \
    echo "Installed-Size: $INSTALLED_SIZE" >> "$DEB_DIR/DEBIAN/control"

# Build the package
dpkg-deb --build "$DEB_DIR" "$BUILD_DIR/$DEB_FILE"

if [ $? -eq 0 ]; then
    echo_info "Successfully created: $BUILD_DIR/$DEB_FILE"
    
    # Show package info
    echo_info "Package information:"
    dpkg-deb --info "$BUILD_DIR/$DEB_FILE"
    
    echo_info "Package contents:"
    dpkg-deb --contents "$BUILD_DIR/$DEB_FILE"
    
    # Test the package (requires root)
    if [ "$EUID" -eq 0 ]; then
        echo_info "Testing package installation (as root)..."
        dpkg --dry-run -i "$BUILD_DIR/$DEB_FILE"
    else
        echo_warn "Run as root to test package installation"
    fi
    
    echo_info "Debian package build complete!"
    echo_info "Install with: sudo dpkg -i $BUILD_DIR/$DEB_FILE"
    echo_info "Or upload to repository for apt installation"
else
    echo_error "Failed to create Debian package"
    exit 1
fi