#!/bin/bash

# Path: scripts/go.sh

set -e

BLUE='\033[1;34m'
YELLOW='\033[1;33m'
GREEN='\033[1;32m'
RED='\033[1;31m'
NC='\033[0m'

export GVM_ROOT="$HOME/.programming/go"
BOOTSTRAP_GO="$GVM_ROOT/bootstrap"

ARCH="$(uname -m)"

case "$ARCH" in
    x86_64)
        GO_BOOTSTRAP_ARCH="amd64"
        ;;
    aarch64)
        GO_BOOTSTRAP_ARCH="arm64"
        ;;
    *)
        echo -e "${RED}    ERROR:${NC} Unsupported architecture for Go bootstrap: $ARCH"
        exit 1
        ;;
esac

echo -e "${BLUE}    LOG:${YELLOW} Setting up Go and GVM in ${GVM_ROOT}...${NC}"

if [ ! -d "$GVM_ROOT/scripts" ]; then
    echo -e "${BLUE}    LOG:${YELLOW} Cloning GVM...${NC}"
    git clone https://github.com/moovweb/gvm.git "$GVM_ROOT"
    rm -rf "$GVM_ROOT/.git"
    echo -e "${BLUE}    LOG:${YELLOW} Configuring GVM scripts...${NC}"
    cp "$GVM_ROOT/scripts/gvm-default" "$GVM_ROOT/scripts/gvm"
    sed -i "s|^GVM_ROOT=.*|GVM_ROOT=\"$GVM_ROOT\"|" "$GVM_ROOT/scripts/gvm"
    
    echo -e "${GREEN}    SUCCESS:${NC} GVM cloned and configured."
else
    echo -e "${GREEN}    SKIP:${NC} GVM already installed."
fi

if [ ! -d "$BOOTSTRAP_GO" ]; then
    echo -e "${BLUE}    LOG:${YELLOW} Downloading Bootstrap Go...${NC}"
    mkdir -p "$BOOTSTRAP_GO"
    
    wget -q "https://go.dev/dl/go1.20.5.linux-${GO_BOOTSTRAP_ARCH}.tar.gz" -O /tmp/go-bootstrap.tar.gz
    tar -C "$BOOTSTRAP_GO" -xzf /tmp/go-bootstrap.tar.gz --strip-components=1
    rm /tmp/go-bootstrap.tar.gz
    
    echo -e "${GREEN}    SUCCESS:${NC} Bootstrap Go installed."
else
    echo -e "${GREEN}    SKIP:${NC} Bootstrap Go already exists."
fi

export PATH="$BOOTSTRAP_GO/bin:$PATH"
export GOROOT_BOOTSTRAP="$BOOTSTRAP_GO"

set +e
source "$GVM_ROOT/scripts/gvm"
set -e

if ! command -v gvm &> /dev/null; then
    echo -e "${RED}    ERROR:${NC} GVM failed to load."
    exit 1
fi

TARGET_VER="go1.24.11"

if ! gvm list | grep -q "$TARGET_VER"; then
    echo -e "${BLUE}    LOG:${YELLOW} Installing ${TARGET_VER}...${NC}"
    gvm install "$TARGET_VER" --prefer-binary
fi

gvm use "$TARGET_VER" --default

echo -e "${GREEN}    SUCCESS:${NC} Go setup completed."
