#!/bin/bash
# Audit build scripts for common issues
# Usage: ./scripts/audit-build-scripts.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

echo "=== Auditing Build Scripts ==="
echo ""

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

WARNINGS=0
ERRORS=0

# Function to report issues
warn() {
    echo -e "${YELLOW}WARNING:${NC} $1"
    ((WARNINGS++))
}

error() {
    echo -e "${RED}ERROR:${NC} $1"
    ((ERRORS++))
}

ok() {
    echo -e "${GREEN}✓${NC} $1"
}

echo "1. Checking for commands used before installation..."
echo "------------------------------------------------"

# Check PM3 stage
PM3_SCRIPT="$PROJECT_DIR/pi-gen/stageDangerousPi/02-pm3-install/00-run-chroot.sh"
if [ -f "$PM3_SCRIPT" ]; then
    # Check if cmake is used before apt-get install
    if grep -q "cmake" "$PM3_SCRIPT"; then
        if ! grep -B50 "cmake" "$PM3_SCRIPT" | grep -q "apt-get install.*cmake"; then
            warn "PM3: cmake used but may not be installed"
        else
            ok "PM3: cmake installation verified"
        fi
    fi

    # Check for git before installation
    if grep -q "git clone" "$PM3_SCRIPT"; then
        if ! grep -B50 "git clone" "$PM3_SCRIPT" | grep -q "apt-get install.*git"; then
            warn "PM3: git used but may not be installed"
        else
            ok "PM3: git installation verified"
        fi
    fi
fi

# Check DangerousPi stage
DTPI_SCRIPT="$PROJECT_DIR/pi-gen/stageDangerousPi/04-dangerous-pi/00-run-chroot.sh"
if [ -f "$DTPI_SCRIPT" ]; then
    # Check for pip3
    if grep -q "pip3 install" "$DTPI_SCRIPT"; then
        if ! grep -B50 "pip3 install" "$DTPI_SCRIPT" | grep -q "apt-get install.*python3-pip\|command -v pip3"; then
            error "DangerousPi: pip3 used but not installed"
        else
            ok "DangerousPi: pip3 installation check present"
        fi
    fi
fi

echo ""
echo "2. Checking for missing directory creation..."
echo "-------------------------------------------"

# Check WiFi AP script
WIFI_SCRIPT="$PROJECT_DIR/pi-gen/stageDangerousPi/01-Wireless-AP/00-run-chroot.sh"
if [ -f "$WIFI_SCRIPT" ]; then
    # Check for directory writes
    DIRS_WRITTEN=$(grep -n "cat >" "$WIFI_SCRIPT" | grep -oE '/etc/[^/]+(/[^/]+)*/' | sort -u)
    for dir in $DIRS_WRITTEN; do
        dir_parent=$(dirname "$dir")
        if ! grep -q "mkdir -p $dir_parent\|mkdir -p $dir" "$WIFI_SCRIPT"; then
            warn "WiFi: Writing to $dir without mkdir -p"
        else
            ok "WiFi: $dir directory creation verified"
        fi
    done
fi

echo ""
echo "3. Checking for undefined variables..."
echo "------------------------------------"

for script in "$PROJECT_DIR"/pi-gen/stage*/*/00-run*.sh; do
    if [ -f "$script" ]; then
        stage=$(basename $(dirname $(dirname "$script")))
        substage=$(basename $(dirname "$script"))

        # Check for common undefined vars
        if grep -q '\$ROOTFS_DIR' "$script" && [ "$(basename "$script")" != "00-run.sh" ]; then
            warn "$stage/$substage: Uses \$ROOTFS_DIR in chroot script (should be in 00-run.sh)"
        fi
    fi
done

echo ""
echo "4. Checking for missing error handling..."
echo "---------------------------------------"

for script in "$PROJECT_DIR"/pi-gen/stage*/*/00-run*.sh; do
    if [ -f "$script" ]; then
        stage=$(basename $(dirname $(dirname "$script")))
        substage=$(basename $(dirname "$script"))

        # Check if script has #!/bin/bash -e
        if ! head -1 "$script" | grep -q "bash -e"; then
            warn "$stage/$substage: Missing 'set -e' or '#!/bin/bash -e'"
        else
            ok "$stage/$substage: Error handling enabled"
        fi
    fi
done

echo ""
echo "5. Checking for sudo usage (not allowed in chroot)..."
echo "---------------------------------------------------"

for script in "$PROJECT_DIR"/pi-gen/stage*/*/00-run*.sh; do
    if [ -f "$script" ]; then
        stage=$(basename $(dirname $(dirname "$script")))
        substage=$(basename $(dirname "$script"))

        if grep -q "sudo " "$script"; then
            error "$stage/$substage: Contains 'sudo' commands (not allowed in chroot)"
        fi
    fi
done
ok "No sudo commands found in stage scripts"

echo ""
echo "6. Checking configuration consistency..."
echo "--------------------------------------"

CONFIG="$PROJECT_DIR/pi-gen/config"
if [ -f "$CONFIG" ]; then
    USERNAME=$(grep "FIRST_USER_NAME=" "$CONFIG" | cut -d'"' -f2)
    echo "Configured username: $USERNAME"

    if [ "$USERNAME" != "pi" ]; then
        warn "Username is '$USERNAME' (not standard 'pi')"
        echo "   This is OK if intentional, but verify all scripts handle it correctly"
    else
        ok "Using standard 'pi' username"
    fi

    # Check if QCOW2 is enabled
    if grep -q "USE_QCOW2=1" "$CONFIG"; then
        ok "QCOW2 caching enabled for fast rebuilds"
    else
        warn "QCOW2 caching disabled - rebuilds will be slow"
    fi
fi

echo ""
echo "7. Checking for required EXPORT_IMAGE markers..."
echo "----------------------------------------------"

for stage in "$PROJECT_DIR"/pi-gen/stageDangerousPi; do
    if [ -d "$stage" ]; then
        stage_name=$(basename "$stage")
        if [ -f "$stage/EXPORT_IMAGE" ]; then
            ok "$stage_name: EXPORT_IMAGE present"
        else
            error "$stage_name: Missing EXPORT_IMAGE marker"
        fi
    fi
done

echo ""
echo "=== Audit Summary ==="
echo "Warnings: $WARNINGS"
echo "Errors: $ERRORS"
echo ""

if [ $ERRORS -gt 0 ]; then
    echo -e "${RED}BUILD SCRIPTS HAVE ERRORS - REVIEW REQUIRED${NC}"
    exit 1
elif [ $WARNINGS -gt 0 ]; then
    echo -e "${YELLOW}BUILD SCRIPTS HAVE WARNINGS - REVIEW RECOMMENDED${NC}"
    exit 0
else
    echo -e "${GREEN}ALL CHECKS PASSED${NC}"
    exit 0
fi
