#!/usr/bin/env bash
# Install Terraform
# Supports multiple installation methods

set -euo pipefail

# Colors

log() {
    log_success "[✓] $1"
}

error() {
    log_error "[✗] $1"
    exit 1
}

warn() {
    log_warn "[!] $1"
}

info() {
    log_info "[i] $1"
}

# Check if Terraform is already installed
if command -v terraform &> /dev/null; then
    TERRAFORM_VERSION=$(terraform version -json | grep -o '"terraform_version":"[^"]*' | cut -d'"' -f4 || terraform version | head -n 1)
    log "Terraform is already installed: $TERRAFORM_VERSION"
    exit 0
fi

info "Installing Terraform..."

# Detect OS
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    # Linux
    if command -v snap &> /dev/null; then
        info "Installing via snap..."
        sudo snap install terraform --classic
        log "Terraform installed via snap"
    elif command -v apt-get &> /dev/null; then
        info "Installing via apt (HashiCorp repository)..."
        # Add HashiCorp repository
        curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -
        sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
        sudo apt-get update
        sudo apt-get install -y terraform
        log "Terraform installed via apt"
    else
        warn "Package manager not found. Installing manually..."
        TERRAFORM_VERSION="1.6.0"
        wget -q "https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip"
        unzip -q "terraform_${TERRAFORM_VERSION}_linux_amd64.zip"
        sudo mv terraform /usr/local/bin/
        rm "terraform_${TERRAFORM_VERSION}_linux_amd64.zip"
        log "Terraform installed manually"
    fi
elif [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS
    if command -v brew &> /dev/null; then
        info "Installing via Homebrew..."
        brew install terraform
        log "Terraform installed via Homebrew"
    else
        error "Homebrew not found. Please install Homebrew first: https://brew.sh"
    fi
else
    error "Unsupported OS: $OSTYPE"
fi

# Verify installation
if command -v terraform &> /dev/null; then
    TERRAFORM_VERSION=$(terraform version | head -n 1)
    log "Terraform installed successfully: $TERRAFORM_VERSION"
else
    error "Terraform installation failed"
fi

