#!/bin/bash

# Default settings
DEFAULT_GO_VERSION="1.26.2"
DEFAULT_ARCH="amd64"

# Allow overriding via environment variables or arguments
GO_VERSION="${1:-$DEFAULT_GO_VERSION}"
ARCH="${2:-$DEFAULT_ARCH}"

# Detect architecture if not specified (simple detection)
if [ -z "$2" ]; then
    MACHINE_ARCH=$(uname -m)
    if [ "$MACHINE_ARCH" = "aarch64" ]; then
        ARCH="arm64"
    elif [ "$MACHINE_ARCH" = "x86_64" ]; then
        ARCH="amd64"
    fi
fi

OS="linux"
TAR_FILE="go${GO_VERSION}.${OS}-${ARCH}.tar.gz"
DOWNLOAD_URL="https://go.dev/dl/${TAR_FILE}"

echo "Target Go Version: $GO_VERSION"
echo "Architecture: $ARCH"

# Check if Go is already installed
CURRENT_VERSION=""
if command -v go &> /dev/null; then
    CURRENT_VERSION=$(go version | awk '{print $3}' | sed 's/go//')
    echo "Current Go Version: $CURRENT_VERSION"
fi

# Compare versions
if [ "$CURRENT_VERSION" == "$GO_VERSION" ]; then
    echo "Go $GO_VERSION is already installed. Skipping installation."
else
    echo "Installing/Updating Go to $GO_VERSION..."
    
    # Download
    echo "Downloading from $DOWNLOAD_URL..."
    if command -v wget &> /dev/null; then
        # Keep wget args widely compatible across GNU/busybox variants.
        # -O: output file
        # --tries/--timeout: avoid hanging forever
        wget "$DOWNLOAD_URL" -O "$TAR_FILE" --tries=3 --timeout=30
    elif command -v curl &> /dev/null; then
        # -f: fail on HTTP errors (404/500)
        # -L: follow redirects
        # --retry: retry transient network failures
        curl -fL --retry 3 --connect-timeout 15 --max-time 600 "$DOWNLOAD_URL" -o "$TAR_FILE"
    else
        echo "Error: Neither wget nor curl found. Please install one of them."
        exit 1
    fi

    if [ $? -ne 0 ]; then
        echo "Download failed. URL: $DOWNLOAD_URL"
        exit 1
    fi

    # Remove old installation
    echo "Removing old installation..."
    rm -rf /usr/local/go

    # Extract new installation
    echo "Extracting to /usr/local..."
    tar -C /usr/local -xzf "$TAR_FILE"
    
    if [ $? -eq 0 ]; then
        echo "Installation successful."
        rm -f "$TAR_FILE"
    else
        echo "Extraction failed."
        exit 1
    fi
fi

# Configure PATH in /etc/profile
PROFILE_FILE="/etc/profile"
GO_BIN_PATH="/usr/local/go/bin"
EXPORT_CMD="export PATH=\$PATH:$GO_BIN_PATH"

# Check if PATH is already configured
if grep -q "$GO_BIN_PATH" "$PROFILE_FILE"; then
    echo "PATH already configured in $PROFILE_FILE."
else
    echo "Adding Go binary path to $PROFILE_FILE..."
    echo "$EXPORT_CMD" >> "$PROFILE_FILE"
    echo "PATH configured. Please run 'source $PROFILE_FILE' or re-login to apply changes."
fi

# Verify installation (using the full path since PATH might not be updated in current shell)
/usr/local/go/bin/go version

source $PROFILE_FILE
