#!/bin/bash
#
# Service Migration Helper Script
# This script automates common migration tasks for moving services to GitHub Actions secrets pipeline
#
# Usage: ./scripts/migrate-service.sh <service-name>
# Example: ./scripts/migrate-service.sh flights

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

# Configuration
REPO_BASE_PATH="${REPO_BASE_PATH:-$HOME/Desktop/git-code/tbi-code}"
ENVS_REPO="${ENVS_REPO:-tbi-environments}"
DEVOPS_ENVS_REPO="${DEVOPS_ENVS_REPO:-tbi-devops-environments}"
NAMESPACE="${NAMESPACE:-redtag}"

# Print colored output
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Print usage
usage() {
    cat <<EOF
Usage: $0 <service-name> [options]

Arguments:
  service-name    Short name of the service (e.g., flights, cars, activities, bookings)

Options:
  --help          Show this help message
  --dry-run       Show what would be done without making changes
  --skip-secrets  Skip secrets file creation
  --skip-workflow Skip workflow file creation
  --skip-ci       Skip CI/CD migration

Examples:
  $0 flights
  $0 cars --dry-run
  $0 activities --skip-secrets

Environment Variables:
  REPO_BASE_PATH        Base path for repositories (default: ~/Desktop/git-code/tbi-code)
  ENVS_REPO            Name of environments repo (default: tbi-environments)
  DEVOPS_ENVS_REPO     Name of devops environments repo (default: tbi-devops-environments)
  NAMESPACE            Kubernetes namespace (default: redtag)

EOF
    exit 1
}

# Parse arguments
SERVICE_NAME=""
DRY_RUN=0
SKIP_SECRETS=0
SKIP_WORKFLOW=0
SKIP_CI=0

while [[ $# -gt 0 ]]; do
    case $1 in
        --help)
            usage
            ;;
        --dry-run)
            DRY_RUN=1
            shift
            ;;
        --skip-secrets)
            SKIP_SECRETS=1
            shift
            ;;
        --skip-workflow)
            SKIP_WORKFLOW=1
            shift
            ;;
        --skip-ci)
            SKIP_CI=1
            shift
            ;;
        *)
            if [ -z "$SERVICE_NAME" ]; then
                SERVICE_NAME="$1"
            else
                print_error "Unknown argument: $1"
                usage
            fi
            shift
            ;;
    esac
done

if [ -z "$SERVICE_NAME" ]; then
    print_error "Service name is required"
    usage
fi

# Derived variables
REDTAG_SERVICE="tbi-redtag-mobile-ms-${SERVICE_NAME}"
COPOLO_SERVICE="tbi-copolo-mobile-ms-${SERVICE_NAME}"
REDTAG_REPO="${REPO_BASE_PATH}/${REDTAG_SERVICE}"
COPOLO_REPO="${REPO_BASE_PATH}/${COPOLO_SERVICE}"
ENVS_PATH="${REPO_BASE_PATH}/${ENVS_REPO}"
DEVOPS_ENVS_PATH="${REPO_BASE_PATH}/${DEVOPS_ENVS_REPO}"

print_info "Migration Configuration:"
echo "  Service Name: ${SERVICE_NAME}"
echo "  RedTag Service: ${REDTAG_SERVICE}"
echo "  Copolo Service: ${COPOLO_SERVICE}"
echo "  Namespace: ${NAMESPACE}"
echo "  Dry Run: ${DRY_RUN}"
echo ""

# Verify paths exist
if [ ! -d "$ENVS_PATH" ]; then
    print_error "Environments repo not found at: $ENVS_PATH"
    exit 1
fi

if [ ! -d "$REDTAG_REPO" ]; then
    print_error "RedTag service repo not found at: $REDTAG_REPO"
    exit 1
fi

# Function to execute or simulate command
execute() {
    if [ $DRY_RUN -eq 1 ]; then
        print_info "[DRY RUN] Would execute: $@"
    else
        print_info "Executing: $@"
        eval "$@"
    fi
}

# ===========================
# Phase 1: Secrets Setup
# ===========================
if [ $SKIP_SECRETS -eq 0 ]; then
    print_info "===== Phase 1: Secrets Setup ====="

    # Check if copolo secrets exist to copy from
    if [ -d "$COPOLO_REPO" ]; then
        print_info "Found Copolo service repo, will copy secrets as template"
        COPY_FROM_COPOLO=1
    else
        print_warning "Copolo service repo not found, will create empty secrets"
        COPY_FROM_COPOLO=0
    fi

    for env in dev qa uat; do
        print_info "Processing environment: $env"

        SECRET_FILE="${ENVS_PATH}/${env}/secrets/secrets.${REDTAG_SERVICE}.yaml"

        if [ -f "$SECRET_FILE" ]; then
            print_warning "Secret file already exists: $SECRET_FILE"
            continue
        fi

        if [ $COPY_FROM_COPOLO -eq 1 ]; then
            COPOLO_SECRET_FILE="${ENVS_PATH}/${env}/secrets/secrets.${COPOLO_SERVICE}.yaml"

            if [ -f "$COPOLO_SECRET_FILE" ]; then
                print_info "Copying from Copolo secrets..."

                # Create temp directory
                TEMP_DIR=$(mktemp -d)

                # Decrypt copolo secrets
                execute "cd ${ENVS_PATH}/${env} && sops -d ${COPOLO_SECRET_FILE} > ${TEMP_DIR}/copolo-${env}.yaml"

                # Create new file (you'll need to manually update service-specific values)
                if [ $DRY_RUN -eq 0 ]; then
                    cat > "${TEMP_DIR}/redtag-${env}.yaml" <<EOF
configs:
    dotenv: |-
        # TODO: Update these values from Copolo secrets
        # Copy from: ${TEMP_DIR}/copolo-${env}.yaml
        # Update service-specific credentials and endpoints
EOF
                    print_warning "Template created at: ${TEMP_DIR}/redtag-${env}.yaml"
                    print_warning "Please manually copy/update values from: ${TEMP_DIR}/copolo-${env}.yaml"
                    print_info "After updating, encrypt with:"
                    echo "  cd ${ENVS_PATH}/${env}"
                    echo "  sops -e ${TEMP_DIR}/redtag-${env}.yaml > ${SECRET_FILE}"
                fi
            fi
        else
            # Create empty template
            if [ $DRY_RUN -eq 0 ]; then
                cat > "/tmp/${REDTAG_SERVICE}-${env}-template.yaml" <<EOF
configs:
    dotenv: |-
        DB_HOST=db-${SERVICE_NAME}-postgresql-main-01.${env}.tbidevelopment.ca
        DB_USERNAME=administrator
        DB_PASSWORD=CHANGE_ME
        DB_PORT=5432
        REDIS_HOST=redis-${SERVICE_NAME}.${env}.tbidevelopment.ca
        REDIS_PORT=6379
        REDIS_PASSWORD=""
        REDIS_USERNAME=""
        STAGE=${env}
        AWS_REGION=ca-central-1
        AWS_AUTH_COGNITO_REGION=ca-central-1
        AWS_AUTH_COGNITO_USER_POOL_ID=CHANGE_ME
        AWS_AUTH_COGNITO_CLIENT_ID=CHANGE_ME
        # Add service-specific variables here
EOF
                print_success "Template created: /tmp/${REDTAG_SERVICE}-${env}-template.yaml"
                print_warning "Please update values and encrypt with:"
                echo "  cd ${ENVS_PATH}/${env}"
                echo "  sops -e /tmp/${REDTAG_SERVICE}-${env}-template.yaml > ${SECRET_FILE}"
            fi
        fi
    done

    print_success "Phase 1 complete - Review and encrypt secrets files"
else
    print_warning "Skipping secrets setup"
fi

# ===========================
# Phase 2: GitHub Actions Workflow
# ===========================
if [ $SKIP_WORKFLOW -eq 0 ]; then
    print_info "===== Phase 2: GitHub Actions Workflow ====="

    WORKFLOW_DIR="${REDTAG_REPO}/.github/workflows"
    WORKFLOW_FILE="${WORKFLOW_DIR}/manage-secrets.yml"

    execute "mkdir -p ${WORKFLOW_DIR}"

    if [ -f "$WORKFLOW_FILE" ]; then
        print_warning "Workflow file already exists: $WORKFLOW_FILE"
    else
        # Copy from hotel service as template
        HOTEL_WORKFLOW="${REPO_BASE_PATH}/tbi-redtag-mobile-hotel-service/.github/workflows/manage-secrets.yml"

        if [ -f "$HOTEL_WORKFLOW" ]; then
            execute "cp ${HOTEL_WORKFLOW} ${WORKFLOW_FILE}"

            # Update service name in workflow
            if [ $DRY_RUN -eq 0 ]; then
                # macOS compatible sed
                sed -i '' "s/tbi-redtag-mobile-hotel-service/${REDTAG_SERVICE}/g" "${WORKFLOW_FILE}"
                print_success "Workflow file created and updated: $WORKFLOW_FILE"
            fi
        else
            print_error "Template workflow not found at: $HOTEL_WORKFLOW"
            exit 1
        fi
    fi

    print_success "Phase 2 complete - Commit workflow file to repo"
else
    print_warning "Skipping workflow setup"
fi

# ===========================
# Phase 3: CI/CD Migration
# ===========================
if [ $SKIP_CI -eq 0 ]; then
    print_info "===== Phase 3: CI/CD Migration to tbi-devops-environments ====="

    if [ ! -d "$DEVOPS_ENVS_PATH" ]; then
        print_warning "DevOps environments repo not found at: $DEVOPS_ENVS_PATH"
        print_info "Skipping CI/CD migration"
    else
        for env in dev qa uat redtag-prod; do
            DEVOPS_SERVICE_DIR="${DEVOPS_ENVS_PATH}/${env}/${REDTAG_SERVICE}"

            print_info "Creating directory structure for $env..."
            execute "mkdir -p ${DEVOPS_SERVICE_DIR}/{.circleci,.github/workflows,docker}"

            # Copy CircleCI config
            if [ -f "${REDTAG_REPO}/.circleci/config.yml" ]; then
                execute "cp ${REDTAG_REPO}/.circleci/config.yml ${DEVOPS_SERVICE_DIR}/.circleci/"
            fi

            # Copy GitHub workflows
            if [ -d "${REDTAG_REPO}/.github/workflows" ]; then
                execute "cp -r ${REDTAG_REPO}/.github/workflows/* ${DEVOPS_SERVICE_DIR}/.github/workflows/"
            fi

            # Copy Dockerfile
            if [ -f "${REDTAG_REPO}/Dockerfile" ]; then
                execute "cp ${REDTAG_REPO}/Dockerfile ${DEVOPS_SERVICE_DIR}/docker/"
            fi
        done

        print_success "Phase 3 complete - Commit changes to tbi-devops-environments"
    fi
else
    print_warning "Skipping CI/CD migration"
fi

# ===========================
# Summary
# ===========================
print_info "===== Migration Summary ====="
echo ""
echo "Next steps:"
echo ""
echo "1. Review and encrypt secrets files in tbi-environments:"
echo "   cd ${ENVS_PATH}/dev"
echo "   sops -e -i secrets/secrets.${REDTAG_SERVICE}.yaml"
echo ""
echo "2. Commit secrets to tbi-environments:"
echo "   cd ${ENVS_PATH}"
echo "   git add dev/secrets/secrets.${REDTAG_SERVICE}.yaml"
echo "   git add qa/secrets/secrets.${REDTAG_SERVICE}.yaml"
echo "   git add uat/secrets/secrets.${REDTAG_SERVICE}.yaml"
echo "   git commit -m 'Add secrets for ${REDTAG_SERVICE}'"
echo "   git push origin master"
echo ""
echo "3. Commit workflow to service repo:"
echo "   cd ${REDTAG_REPO}"
echo "   git add .github/workflows/manage-secrets.yml"
echo "   git commit -m 'Add GitHub Actions secrets management workflow'"
echo "   git push origin develop"
echo ""
echo "4. Test the workflow in GitHub Actions"
echo ""
echo "5. Commit CI/CD configs to tbi-devops-environments:"
echo "   cd ${DEVOPS_ENVS_PATH}"
echo "   git add ."
echo "   git commit -m 'Add CI/CD configs for ${REDTAG_SERVICE}'"
echo "   git push origin master"
echo ""
print_success "Migration helper script complete!"
