#!/bin/bash

# GitLab CI/CD Pipeline Generator
# Interactive script to generate customized .gitlab-ci.yml files

set -e

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

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEMPLATES_DIR="$(dirname "$SCRIPT_DIR")/templates"

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}GitLab CI/CD Pipeline Generator${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Function to display menu and get user selection
show_menu() {
    echo -e "${GREEN}Available Pipeline Templates:${NC}"
    echo ""
    echo "1) Node.js CI/CD Pipeline"
    echo "   - npm dependency caching"
    echo "   - Parallel linting and testing"
    echo "   - Multi-environment deployment"
    echo ""
    echo "2) Python CI/CD Pipeline"
    echo "   - Virtual environment caching"
    echo "   - pytest with coverage"
    echo "   - Security scanning with Bandit"
    echo ""
    echo "3) Docker Build and Push"
    echo "   - Multi-stage builds with caching"
    echo "   - Security scanning with Trivy"
    echo "   - Multi-registry support"
    echo ""
    echo "4) Kubernetes Deployment"
    echo "   - kubectl and Helm deployments"
    echo "   - Blue-green and canary strategies"
    echo "   - Multi-environment support"
    echo ""
    echo "5) Security Scanning"
    echo "   - SAST, DAST, dependency scanning"
    echo "   - Container and IaC scanning"
    echo "   - Secret detection"
    echo ""
    echo "6) Go CI/CD Pipeline"
    echo "   - Go module caching"
    echo "   - Cross-platform builds"
    echo "   - Security scanning with gosec"
    echo ""
    echo "0) Exit"
    echo ""
}

# Function to copy template
copy_template() {
    local template_dir=$1
    local output_file=$2

    if [ ! -d "$template_dir" ]; then
        echo -e "${RED}Error: Template directory not found: $template_dir${NC}"
        exit 1
    fi

    if [ -f "$output_file" ]; then
        echo -e "${YELLOW}Warning: $output_file already exists.${NC}"
        read -p "Overwrite? (y/n): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            echo -e "${YELLOW}Cancelled.${NC}"
            exit 0
        fi
    fi

    cp "$template_dir/.gitlab-ci.yml" "$output_file"
    echo -e "${GREEN}✓ Pipeline configuration generated: $output_file${NC}"
}

# Function to customize template
customize_template() {
    local output_file=$1
    local template_type=$2

    echo ""
    echo -e "${BLUE}Customization Options:${NC}"
    echo ""

    case $template_type in
        node)
            read -p "Node.js version (default: 20): " node_version
            node_version=${node_version:-20}
            sed -i.bak "s/NODE_VERSION: \"20\"/NODE_VERSION: \"$node_version\"/" "$output_file"
            rm -f "${output_file}.bak"
            echo -e "${GREEN}✓ Node.js version set to: $node_version${NC}"
            ;;
        python)
            read -p "Python version (default: 3.12): " python_version
            python_version=${python_version:-3.12}
            sed -i.bak "s/PYTHON_VERSION: \"3.12\"/PYTHON_VERSION: \"$python_version\"/" "$output_file"
            rm -f "${output_file}.bak"
            echo -e "${GREEN}✓ Python version set to: $python_version${NC}"
            ;;
        go)
            read -p "Go version (default: 1.22): " go_version
            go_version=${go_version:-1.22}
            sed -i.bak "s/GO_VERSION: \"1.22\"/GO_VERSION: \"$go_version\"/" "$output_file"
            rm -f "${output_file}.bak"
            echo -e "${GREEN}✓ Go version set to: $go_version${NC}"
            ;;
        k8s)
            read -p "Enable Helm deployment? (y/n): " use_helm
            if [[ ! $use_helm =~ ^[Yy]$ ]]; then
                # Comment out Helm jobs
                sed -i.bak '/deploy_.*_helm:/,/when: manual/s/^/#/' "$output_file"
                rm -f "${output_file}.bak"
                echo -e "${GREEN}✓ Helm deployment disabled${NC}"
            fi
            ;;
    esac
}

# Function to show next steps
show_next_steps() {
    local template_type=$1

    echo ""
    echo -e "${BLUE}========================================${NC}"
    echo -e "${GREEN}Next Steps:${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo ""
    echo "1. Review and customize the generated .gitlab-ci.yml file"
    echo "2. Ensure required CI/CD variables are set in GitLab:"
    echo ""

    case $template_type in
        node)
            echo "   - No additional variables required for basic setup"
            echo "   - For deployment, configure environment-specific variables"
            ;;
        python)
            echo "   - No additional variables required for basic setup"
            echo "   - For PyPI publishing, set: TWINE_USERNAME, TWINE_PASSWORD"
            ;;
        docker)
            echo "   - CI_REGISTRY_USER and CI_REGISTRY_PASSWORD (auto-configured)"
            echo "   - For external registries: DOCKER_HUB_USERNAME, DOCKER_HUB_TOKEN"
            ;;
        k8s)
            echo "   - KUBE_CONFIG_DEV: Base64-encoded kubeconfig for dev"
            echo "   - KUBE_CONFIG_STAGING: Base64-encoded kubeconfig for staging"
            echo "   - KUBE_CONFIG_PROD: Base64-encoded kubeconfig for production"
            ;;
        security)
            echo "   - No additional variables required (GitLab built-in)"
            echo "   - For DAST: Configure DAST_WEBSITE variable"
            ;;
        go)
            echo "   - No additional variables required for basic setup"
            echo "   - For releases, ensure tag-based triggers are configured"
            ;;
    esac

    echo ""
    echo "3. Validate the pipeline:"
    echo "   ./scripts/validate-gitlab-ci.sh .gitlab-ci.yml"
    echo ""
    echo "4. Commit and push to trigger the pipeline:"
    echo "   git add .gitlab-ci.yml"
    echo "   git commit -m 'Add GitLab CI/CD pipeline'"
    echo "   git push"
    echo ""
}

# Main script
main() {
    while true; do
        show_menu
        read -p "Select a template (0-6): " choice

        case $choice in
            1)
                OUTPUT_FILE="${1:-.gitlab-ci.yml}"
                copy_template "$TEMPLATES_DIR/node-ci-cd" "$OUTPUT_FILE"
                customize_template "$OUTPUT_FILE" "node"
                show_next_steps "node"
                break
                ;;
            2)
                OUTPUT_FILE="${1:-.gitlab-ci.yml}"
                copy_template "$TEMPLATES_DIR/python-ci-cd" "$OUTPUT_FILE"
                customize_template "$OUTPUT_FILE" "python"
                show_next_steps "python"
                break
                ;;
            3)
                OUTPUT_FILE="${1:-.gitlab-ci.yml}"
                copy_template "$TEMPLATES_DIR/docker-build-push" "$OUTPUT_FILE"
                customize_template "$OUTPUT_FILE" "docker"
                show_next_steps "docker"
                break
                ;;
            4)
                OUTPUT_FILE="${1:-.gitlab-ci.yml}"
                copy_template "$TEMPLATES_DIR/kubernetes-deploy" "$OUTPUT_FILE"
                customize_template "$OUTPUT_FILE" "k8s"
                show_next_steps "k8s"
                break
                ;;
            5)
                OUTPUT_FILE="${1:-.gitlab-ci.yml}"
                copy_template "$TEMPLATES_DIR/security-scanning" "$OUTPUT_FILE"
                show_next_steps "security"
                break
                ;;
            6)
                OUTPUT_FILE="${1:-.gitlab-ci.yml}"
                copy_template "$TEMPLATES_DIR/go-ci-cd" "$OUTPUT_FILE"
                customize_template "$OUTPUT_FILE" "go"
                show_next_steps "go"
                break
                ;;
            0)
                echo -e "${GREEN}Goodbye!${NC}"
                exit 0
                ;;
            *)
                echo -e "${RED}Invalid selection. Please try again.${NC}"
                echo ""
                ;;
        esac
    done
}

# Run main function
main "$@"
