#!/bin/bash
#
# Helm Chart Generator - Interactive Chart Creation Script
# Generates production-ready Helm charts from templates
#
# Usage: ./generate-helm-chart.sh [chart-type] [chart-name]
#

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"

# Function to print colored output
print_info() {
    echo -e "${BLUE}ℹ${NC} $1"
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

# Function to display help
show_help() {
    cat << EOF
Helm Chart Generator

Usage: $0 [OPTIONS]

Options:
    -h, --help          Show this help message
    -t, --type TYPE     Chart type (web-application, stateful-application, microservice, cronjob, redis)
    -n, --name NAME     Chart name
    -o, --output DIR    Output directory (default: current directory)

Interactive Mode:
    Run without arguments for interactive prompts

Chart Types:
    web-application       - Full-featured web application with ingress, HPA
    stateful-application  - StatefulSet with persistent storage (databases)
    microservice          - Lightweight microservice deployment
    cronjob               - Scheduled job/batch processing
    redis                 - Redis cache deployment

Examples:
    $0 -t web-application -n my-app
    $0 -t cronjob -n backup-job -o ./charts
    $0  # Interactive mode

EOF
}

# Parse command line arguments
CHART_TYPE=""
CHART_NAME=""
OUTPUT_DIR="."

while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        -t|--type)
            CHART_TYPE="$2"
            shift 2
            ;;
        -n|--name)
            CHART_NAME="$2"
            shift 2
            ;;
        -o|--output)
            OUTPUT_DIR="$2"
            shift 2
            ;;
        *)
            print_error "Unknown option: $1"
            show_help
            exit 1
            ;;
    esac
done

# Interactive mode if arguments not provided
if [[ -z "$CHART_TYPE" ]]; then
    echo
    print_info "Available chart types:"
    echo "  1) web-application       - Full-featured web application"
    echo "  2) stateful-application  - Stateful apps with persistence"
    echo "  3) microservice          - Lightweight microservice"
    echo "  4) cronjob               - Scheduled jobs"
    echo "  5) redis                 - Redis cache"
    echo
    read -p "Select chart type (1-5): " type_selection

    case $type_selection in
        1) CHART_TYPE="web-application" ;;
        2) CHART_TYPE="stateful-application" ;;
        3) CHART_TYPE="microservice" ;;
        4) CHART_TYPE="cronjob" ;;
        5) CHART_TYPE="redis" ;;
        *)
            print_error "Invalid selection"
            exit 1
            ;;
    esac
fi

if [[ -z "$CHART_NAME" ]]; then
    read -p "Enter chart name: " CHART_NAME
fi

# Validate chart type
if [[ ! -d "$TEMPLATES_DIR/$CHART_TYPE" ]]; then
    print_error "Chart type '$CHART_TYPE' not found"
    print_info "Available types: web-application, stateful-application, microservice, cronjob, redis"
    exit 1
fi

# Validate chart name
if [[ ! "$CHART_NAME" =~ ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ ]]; then
    print_error "Invalid chart name. Must be lowercase alphanumeric with hyphens"
    exit 1
fi

# Create output directory
OUTPUT_PATH="$OUTPUT_DIR/$CHART_NAME"
if [[ -d "$OUTPUT_PATH" ]]; then
    print_warning "Directory '$OUTPUT_PATH' already exists"
    read -p "Overwrite? (y/N): " confirm
    if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
        print_info "Aborted"
        exit 0
    fi
    rm -rf "$OUTPUT_PATH"
fi

print_info "Creating Helm chart: $CHART_NAME (type: $CHART_TYPE)"

# Copy template
cp -r "$TEMPLATES_DIR/$CHART_TYPE" "$OUTPUT_PATH"

# Customize Chart.yaml
if [[ -f "$OUTPUT_PATH/Chart.yaml" ]]; then
    # Update chart name
    if command -v sed >/dev/null 2>&1; then
        # macOS compatible sed
        sed -i '' "s/^name:.*/name: $CHART_NAME/" "$OUTPUT_PATH/Chart.yaml" 2>/dev/null || \
        sed -i "s/^name:.*/name: $CHART_NAME/" "$OUTPUT_PATH/Chart.yaml"
    fi
fi

# Create README if it doesn't exist
if [[ ! -f "$OUTPUT_PATH/README.md" ]]; then
    cat > "$OUTPUT_PATH/README.md" << EOF
# $CHART_NAME

## Overview
Helm chart for $CHART_NAME based on $CHART_TYPE template.

## Installation

\`\`\`bash
helm install $CHART_NAME .
\`\`\`

## Configuration

See \`values.yaml\` for configuration options.

## Upgrade

\`\`\`bash
helm upgrade $CHART_NAME .
\`\`\`

## Uninstall

\`\`\`bash
helm uninstall $CHART_NAME
\`\`\`
EOF
fi

# Success message
echo
print_success "Helm chart created successfully!"
echo
print_info "Chart location: $OUTPUT_PATH"
print_info "Chart type: $CHART_TYPE"
echo
print_info "Next steps:"
echo "  1. cd $OUTPUT_PATH"
echo "  2. Edit values.yaml to customize configuration"
echo "  3. helm lint . (validate chart)"
echo "  4. helm template . (preview rendered templates)"
echo "  5. helm install $CHART_NAME ."
echo
print_info "To validate the chart, run:"
echo "  $SCRIPT_DIR/validate-helm-chart.sh $OUTPUT_PATH"
echo
