#!/usr/bin/env bash

set -e

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

echo -e "${BLUE}╔════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║   Terraform Backend Initializer - Skill #13║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════════╝${NC}"
echo

# Check if AWS CLI is installed
if ! command -v aws &> /dev/null; then
    echo -e "${RED}✗ AWS CLI not found${NC}"
    echo "Install: https://aws.amazon.com/cli/"
    exit 1
fi

# Get AWS region
AWS_REGION=$(aws configure get region 2>/dev/null || echo "us-east-1")
echo -e "${BLUE}AWS Region: ${AWS_REGION}${NC}"
echo

# Get inputs
read -p "Enter S3 bucket name for Terraform state: " BUCKET_NAME
if [ -z "$BUCKET_NAME" ]; then
    echo -e "${RED}Bucket name is required${NC}"
    exit 1
fi

read -p "Enter DynamoDB table name for state locking [terraform-state-lock]: " TABLE_NAME
TABLE_NAME=${TABLE_NAME:-terraform-state-lock}

echo
echo -e "${BLUE}════════════════════════════════════════════${NC}"
echo "S3 Bucket:       $BUCKET_NAME"
echo "DynamoDB Table:  $TABLE_NAME"
echo "Region:          $AWS_REGION"
echo -e "${BLUE}════════════════════════════════════════════${NC}"
echo
read -p "Create these resources? [Y/n]: " CONFIRM
CONFIRM=${CONFIRM:-Y}

if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
    echo "Cancelled."
    exit 0
fi

echo
echo -e "${GREEN}Creating Terraform backend infrastructure...${NC}"
echo

# Create temporary Terraform configuration
TMP_DIR=$(mktemp -d)
trap "rm -rf $TMP_DIR" EXIT

cat > "$TMP_DIR/backend.tf" <<EOF
terraform {
  required_version = ">= 1.6"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "$AWS_REGION"
}

# KMS Key for encryption
resource "aws_kms_key" "terraform_state" {
  description             = "KMS key for Terraform state encryption"
  deletion_window_in_days = 10
  enable_key_rotation     = true

  tags = {
    Name      = "terraform-state-key"
    ManagedBy = "terraform"
    Purpose   = "state-encryption"
  }
}

resource "aws_kms_alias" "terraform_state" {
  name          = "alias/terraform-state"
  target_key_id = aws_kms_key.terraform_state.key_id
}

# S3 Bucket for state
resource "aws_s3_bucket" "terraform_state" {
  bucket = "$BUCKET_NAME"

  tags = {
    Name      = "Terraform State Bucket"
    ManagedBy = "terraform"
    Purpose   = "state-storage"
  }
}

# Enable versioning
resource "aws_s3_bucket_versioning" "terraform_state" {
  bucket = aws_s3_bucket.terraform_state.id

  versioning_configuration {
    status = "Enabled"
  }
}

# Enable encryption
resource "aws_s3_bucket_server_side_encryption_configuration" "terraform_state" {
  bucket = aws_s3_bucket.terraform_state.id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm     = "aws:kms"
      kms_master_key_id = aws_kms_key.terraform_state.arn
    }
  }
}

# Block public access
resource "aws_s3_bucket_public_access_block" "terraform_state" {
  bucket = aws_s3_bucket.terraform_state.id

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

# Enable logging
resource "aws_s3_bucket_logging" "terraform_state" {
  bucket = aws_s3_bucket.terraform_state.id

  target_bucket = aws_s3_bucket.terraform_state.id
  target_prefix = "log/"
}

# DynamoDB table for state locking
resource "aws_dynamodb_table" "terraform_locks" {
  name         = "$TABLE_NAME"
  billing_mode = "PAY_PER_REQUEST"
  hash_key     = "LockID"

  attribute {
    name = "LockID"
    type = "S"
  }

  tags = {
    Name      = "Terraform State Lock Table"
    ManagedBy = "terraform"
    Purpose   = "state-locking"
  }
}

# Outputs
output "bucket_name" {
  description = "S3 bucket name for Terraform state"
  value       = aws_s3_bucket.terraform_state.id
}

output "dynamodb_table_name" {
  description = "DynamoDB table name for state locking"
  value       = aws_dynamodb_table.terraform_locks.id
}

output "kms_key_id" {
  description = "KMS key ID for state encryption"
  value       = aws_kms_key.terraform_state.id
}

output "kms_key_arn" {
  description = "KMS key ARN for state encryption"
  value       = aws_kms_key.terraform_state.arn
}

output "region" {
  description = "AWS region"
  value       = "$AWS_REGION"
}
EOF

# Initialize and apply
cd "$TMP_DIR"
echo -e "${YELLOW}Initializing Terraform...${NC}"
terraform init

echo
echo -e "${YELLOW}Planning infrastructure...${NC}"
terraform plan

echo
read -p "Apply this plan? [Y/n]: " APPLY_CONFIRM
APPLY_CONFIRM=${APPLY_CONFIRM:-Y}

if [[ ! "$APPLY_CONFIRM" =~ ^[Yy]$ ]]; then
    echo "Cancelled."
    exit 0
fi

echo
echo -e "${YELLOW}Creating backend infrastructure...${NC}"
terraform apply -auto-approve

echo
echo -e "${GREEN}✓ Backend infrastructure created successfully!${NC}"
echo

# Get outputs
KMS_KEY_ARN=$(terraform output -raw kms_key_arn)

# Generate backend configuration
echo -e "${BLUE}════════════════════════════════════════════${NC}"
echo -e "${GREEN}Backend Configuration${NC}"
echo -e "${BLUE}════════════════════════════════════════════${NC}"
echo
echo "Add this to your Terraform configuration:"
echo
cat <<EOF
terraform {
  backend "s3" {
    bucket         = "$BUCKET_NAME"
    key            = "path/to/terraform.tfstate"  # Change this per environment
    region         = "$AWS_REGION"
    encrypt        = true
    dynamodb_table = "$TABLE_NAME"
    kms_key_id     = "$KMS_KEY_ARN"
  }
}
EOF

echo
echo -e "${BLUE}════════════════════════════════════════════${NC}"
echo
echo "Next steps:"
echo "  1. Copy the backend configuration above"
echo "  2. Add it to your Terraform project"
echo "  3. Run 'terraform init' to migrate state"
echo
echo -e "${GREEN}Happy Terraforming! 🚀${NC}"
