#!/usr/bin/env bash
set -e

SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
cd "$SCRIPT_DIR"

# Function to print messages
log() {
	echo "$(date '+%Y-%m-%d %H:%M:%S') - $1"
}

# Function to print success messages (green)
echo_success() {
	printf "\033[0;32m✓ %s\033[0m\n" "$1"
}

# Function to print warning messages (yellow)
echo_warn() {
	printf "\033[0;33mWARN: %s\033[0m\n" "$1"
}

log "Starting setup..."

log "Installing templ..."
go install github.com/a-h/templ/cmd/templ@latest

log "Installing golangci-lint..."
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest

log "Checking PATH environment variable..."

# Determine GOPATH/bin
GOPATH_BIN=$(go env GOPATH)/bin

# Check if GOPATH/bin could be determined
if [ -z "$GOPATH_BIN" ] || [ "$GOPATH_BIN" = "/bin" ]; then
	echo_warn "Could not determine GOPATH/bin. Please ensure GOPATH is set correctly."
else
	# Use awk to check if GOPATH_BIN is a distinct component in PATH
	if echo "$PATH" | awk -v path_to_check="$GOPATH_BIN" 'BEGIN { FS=":"; found=0 } { for(i=1; i<=NF; i++) if ($i == path_to_check) { found=1; exit 0 } } END { exit !found }'; then
		echo_success "$GOPATH_BIN appears to be in your PATH."
	else
		echo_warn "$GOPATH_BIN does not appear to be in your PATH."
		echo "         Please add it to your shell configuration (e.g., .zshrc, .bashrc):"
		echo "         export PATH=\"$PATH:$GOPATH_BIN\""
	fi
fi

# Use printf for the final success message too
printf "\033[0;32m✓ %s\033[0m\n" "Setup complete."
