#!/bin/bash

#
# Ansible Playbook Validator
# Validates playbook syntax and best practices
#

set -e

PLAYBOOK="${1:-playbook.yml}"

echo "Validating Ansible playbook: $PLAYBOOK"
echo ""

ERRORS=0
WARNINGS=0

# Check if ansible is installed
if ! command -v ansible &> /dev/null; then
    echo "❌ Ansible is not installed"
    exit 1
fi

# Check if playbook exists
if [ ! -f "$PLAYBOOK" ]; then
    echo "❌ Playbook not found: $PLAYBOOK"
    exit 1
fi

# Syntax check
echo "Checking YAML syntax..."
if ansible-playbook "$PLAYBOOK" --syntax-check > /dev/null 2>&1; then
    echo "✅ YAML syntax is valid"
else
    echo "❌ YAML syntax errors found"
    ansible-playbook "$PLAYBOOK" --syntax-check
    ERRORS=$((ERRORS + 1))
fi

# Check for ansible-lint
if command -v ansible-lint &> /dev/null; then
    echo ""
    echo "Running ansible-lint..."
    if ansible-lint "$PLAYBOOK" 2>&1 | head -20; then
        echo "✅ Passed ansible-lint"
    else
        echo "⚠️  ansible-lint found issues"
        WARNINGS=$((WARNINGS + 1))
    fi
else
    echo "⚠️  ansible-lint not installed (recommended: pip install ansible-lint)"
    WARNINGS=$((WARNINGS + 1))
fi

# Check for common issues
echo ""
echo "Checking best practices..."

if grep -q "become: yes" "$PLAYBOOK"; then
    echo "✅ Uses privilege escalation"
fi

if grep -q "handlers:" "$PLAYBOOK"; then
    echo "✅ Uses handlers"
fi

if grep -q "when:" "$PLAYBOOK"; then
    echo "✅ Uses conditionals"
fi

# Check for hardcoded passwords
if grep -iE "(password|secret|token|key).*:" "$PLAYBOOK" | grep -v "{{" | grep -v "#"; then
    echo "⚠️  Possible hardcoded secrets detected - use ansible-vault!"
    WARNINGS=$((WARNINGS + 1))
fi

# Summary
echo ""
echo "================================"
echo "Validation Summary:"
echo "  Errors: $ERRORS"
echo "  Warnings: $WARNINGS"
echo ""

if [ $ERRORS -eq 0 ]; then
    echo "✅ Validation passed!"
    if [ $WARNINGS -gt 0 ]; then
        echo "⚠️  $WARNINGS warnings found (review recommended)"
    fi
    exit 0
else
    echo "❌ Validation failed with $ERRORS errors"
    exit 1
fi
