#!/usr/bin/env bash
# This file is managed by Terraform in github-control repository
# Do not edit this file, all changes will be overwritten
# If you need to change this file, create a pull request in
# https://github.com/infrahouse/github-control

# Validates commit messages follow conventional commit format
# See: https://www.conventionalcommits.org/

set -e

commit_msg_file=$1
commit_msg=$(cat "$commit_msg_file")

# Skip validation for merge commits
if echo "$commit_msg" | grep -qE '^Merge (branch|pull request)'; then
    exit 0
fi

# Conventional commit pattern
# Supports: type(scope): description or type: description
# Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert, security
# Optional ! for breaking changes: feat!: description
pattern='^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert|security)(\(.+\))?!?: .{1,}'

if ! echo "$commit_msg" | grep -qE "$pattern"; then
    echo "❌ Invalid commit message format"
    echo ""
    echo "📝 Commit message must follow Conventional Commits:"
    echo ""
    echo "  <type>[optional scope][!]: <description>"
    echo ""
    echo "  [optional body]"
    echo ""
    echo "  [optional footer(s)]"
    echo ""
    echo "Types:"
    echo "  feat:     ✨ New feature"
    echo "  fix:      🐛 Bug fix"
    echo "  docs:     📚 Documentation changes"
    echo "  security: 🔒 Security improvements"
    echo "  refactor: ♻️  Code refactoring (no functional changes)"
    echo "  perf:     ⚡ Performance improvement"
    echo "  test:     ✅ Adding or updating tests"
    echo "  build:    🔧 Build system or dependency changes"
    echo "  ci:       👷 CI/CD configuration changes"
    echo "  chore:    🔨 Maintenance tasks"
    echo "  revert:   ⏪ Revert a previous commit"
    echo "  style:    💄 Code style changes (formatting, etc.)"
    echo ""
    echo "Breaking changes:"
    echo "  Use ! after type: feat!: breaking change description"
    echo ""
    echo "Examples:"
    echo "  ✓ feat: add deregistration delay configuration"
    echo "  ✓ fix: correct unhealthy threshold variable name"
    echo "  ✓ security: add S3 bucket encryption for access logs"
    echo "  ✓ docs: improve variable descriptions using HEREDOC"
    echo "  ✓ feat(alb): add listener rule priority documentation"
    echo "  ✓ feat!: remove deprecated variables (breaking change)"
    echo ""
    echo "Your message:"
    echo "  $commit_msg"
    echo ""
    echo "See: https://www.conventionalcommits.org/"
    exit 1
fi

# Success - message is valid
exit 0
