#!/usr/bin/env bash

set -e

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

# Counters
ERRORS=0
WARNINGS=0

echo -e "${BLUE}╔════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║   Terraform Validator - Skill #13          ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════════╝${NC}"
echo

# Check if terraform is installed
if ! command -v terraform &> /dev/null; then
    echo -e "${RED}✗ Terraform not found${NC}"
    echo "Install: https://www.terraform.io/downloads"
    exit 1
fi

echo -e "${GREEN}Terraform version:${NC} $(terraform version -json | jq -r .terraform_version 2>/dev/null || terraform version | head -1)"
echo

# Get target directory
TARGET_DIR="${1:-.}"
cd "$TARGET_DIR"

echo -e "${BLUE}Validating: $(pwd)${NC}"
echo

# 1. Terraform Format Check
echo -e "${YELLOW}[1/5] Checking Terraform formatting...${NC}"
if terraform fmt -check -recursive; then
    echo -e "${GREEN}✓ Formatting is correct${NC}"
else
    echo -e "${YELLOW}⚠ Formatting issues found (run 'terraform fmt -recursive' to fix)${NC}"
    WARNINGS=$((WARNINGS + 1))
fi
echo

# 2. Terraform Validate
echo -e "${YELLOW}[2/5] Running Terraform validate...${NC}"
if [ ! -d ".terraform" ]; then
    echo "Initializing Terraform (backend=false)..."
    terraform init -backend=false > /dev/null 2>&1
fi

if terraform validate; then
    echo -e "${GREEN}✓ Validation passed${NC}"
else
    echo -e "${RED}✗ Validation failed${NC}"
    ERRORS=$((ERRORS + 1))
fi
echo

# 3. tflint (if installed)
echo -e "${YELLOW}[3/5] Running tflint...${NC}"
if command -v tflint &> /dev/null; then
    if tflint --init > /dev/null 2>&1 && tflint; then
        echo -e "${GREEN}✓ tflint passed${NC}"
    else
        echo -e "${YELLOW}⚠ tflint found issues${NC}"
        WARNINGS=$((WARNINGS + 1))
    fi
else
    echo -e "${YELLOW}⚠ tflint not installed (optional)${NC}"
    echo "Install: https://github.com/terraform-linters/tflint"
fi
echo

# 4. tfsec (if installed)
echo -e "${YELLOW}[4/5] Running tfsec security scan...${NC}"
if command -v tfsec &> /dev/null; then
    if tfsec . --minimum-severity MEDIUM --no-color; then
        echo -e "${GREEN}✓ tfsec security scan passed${NC}"
    else
        echo -e "${YELLOW}⚠ tfsec found security issues${NC}"
        WARNINGS=$((WARNINGS + 1))
    fi
else
    echo -e "${YELLOW}⚠ tfsec not installed (optional but recommended)${NC}"
    echo "Install: https://github.com/aquasecurity/tfsec"
fi
echo

# 5. Check for common issues
echo -e "${YELLOW}[5/5] Checking for common issues...${NC}"

# Check for hardcoded secrets
if grep -r -i "password.*=.*\".*\"" --include="*.tf" . 2>/dev/null | grep -v "random_password" | grep -v "data.*secretsmanager" | grep -q .; then
    echo -e "${RED}✗ Possible hardcoded passwords found${NC}"
    grep -r -i "password.*=.*\".*\"" --include="*.tf" . 2>/dev/null | grep -v "random_password" | grep -v "data.*secretsmanager" || true
    ERRORS=$((ERRORS + 1))
else
    echo -e "${GREEN}✓ No obvious hardcoded secrets${NC}"
fi

# Check for missing sensitive flags
if grep -r "password\|secret\|key" --include="outputs.tf" . 2>/dev/null | grep -v "sensitive.*=.*true" | grep -q "output"; then
    echo -e "${YELLOW}⚠ Outputs with 'password', 'secret', or 'key' should be marked sensitive${NC}"
    WARNINGS=$((WARNINGS + 1))
fi

# Check for terraform.tfstate in git
if [ -f ".gitignore" ]; then
    if ! grep -q "\.tfstate" .gitignore; then
        echo -e "${RED}✗ .tfstate not in .gitignore${NC}"
        ERRORS=$((ERRORS + 1))
    else
        echo -e "${GREEN}✓ .tfstate in .gitignore${NC}"
    fi
fi

echo

# Summary
echo -e "${BLUE}════════════════════════════════════════════${NC}"
echo -e "${BLUE}Validation Summary${NC}"
echo -e "${BLUE}════════════════════════════════════════════${NC}"

if [ $ERRORS -eq 0 ] && [ $WARNINGS -eq 0 ]; then
    echo -e "${GREEN}✓ All checks passed!${NC}"
    exit 0
elif [ $ERRORS -eq 0 ]; then
    echo -e "${YELLOW}⚠ Passed with $WARNINGS warning(s)${NC}"
    exit 0
else
    echo -e "${RED}✗ Failed with $ERRORS error(s) and $WARNINGS warning(s)${NC}"
    exit 1
fi
