#!/bin/bash
# Simple CI/CD testing without Gitea instance
# Tests the workflow steps locally using docker containers

set -e

echo "🧪 Simple CI/CD Testing (No Gitea Required)"
echo "=========================================="

# 1. YAML Linting
echo "1. Running YAML linting..."
if [ -f ".yamllint.yaml" ]; then
    docker run --rm -v $(pwd):/workspace -w /workspace pipelinecomponents/yamllint:latest \
        yamllint -c .yamllint.yaml .gitea/workflows/
else
    docker run --rm -v $(pwd):/workspace -w /workspace pipelinecomponents/yamllint:latest \
        yamllint .gitea/workflows/
fi
echo "✅ YAML linting passed"

# 2. YAML Validation
echo "2. Running YAML validation..."
WORKFLOW_FILES=(".gitea/workflows/go-ci-cd.yaml" ".gitea/workflows/dockerimage.yaml")
for file in "${WORKFLOW_FILES[@]}"; do
    docker run --rm -v $(pwd):/workspace -w /workspace mikefarah/yq:latest eval '.' "$file" > /dev/null
done
echo "✅ YAML validation passed"

# 3. Workflow Structure Validation
echo "3. Running workflow structure validation..."
./scripts/cicd/validate-workflow.sh

# 4. Simulate Build Job
echo "4. Simulating build-test job..."
docker run --rm -v $(pwd):/workspace -w /workspace golang:1.26.1 bash -c "
    apt-get update -qq && apt-get install -y -qq git > /dev/null && \
    go mod tidy && \
    go build ./... && \
    go test ./... -cover -v
"
echo "✅ Build and test completed"

# 5. Simulate Lint Job
echo "5. Simulating lint-format job..."
docker run --rm -v $(pwd):/workspace -w /workspace golang:1.26.1 bash -c "
    go fmt ./... && \
    go vet ./... && \
    echo 'Formatting check passed'
"
echo "✅ Linting completed"

echo ""
echo "🎉 Simple CI/CD Testing Complete!"
echo "=========================================="
echo "✅ All workflow steps validated locally"
echo "📝 Workflow is ready for Gitea deployment"
echo ""
echo "🚀 To deploy to Gitea:"
echo "  1. Create config/runner file with your Gitea runner token"
echo "  2. Set GITEA_RUNNER_REGISTRATION_TOKEN environment variable"
echo "  3. Run: docker compose -f docker-compose.cicd-test.yml up"
