#!/bin/bash

# ---------------------------------------------------------------------------------
# Golang install recipe
# Fetches the latest stable Go release, installs to /usr/local/go,
# then installs go-based CLI tools.
# ---------------------------------------------------------------------------------

set -e

# ---------------------------------------------------------------------------------
# Detect architecture
# ---------------------------------------------------------------------------------
ARCH=$(dpkg --print-architecture)
case "$ARCH" in
    amd64) GO_ARCH="amd64" ;;
    arm64) GO_ARCH="arm64" ;;
    *)
        echo "❌ Unsupported architecture: $ARCH"
        exit 1
        ;;
esac

# ---------------------------------------------------------------------------------
# Fetch latest stable Go version
# ---------------------------------------------------------------------------------
echo "🔍 Fetching latest stable Go version..."
GO_VERSION=$(curl -fsSL "https://go.dev/dl/?mode=json" | grep -o '"version":"go[^"]*"' | head -1 | grep -o 'go[0-9.]*')

if [ -z "$GO_VERSION" ]; then
    echo "❌ Failed to fetch latest Go version."
    exit 1
fi

echo "✅ Latest Go version: $GO_VERSION"

# ---------------------------------------------------------------------------------
# Download and install
# ---------------------------------------------------------------------------------
TARBALL="${GO_VERSION}.linux-${GO_ARCH}.tar.gz"
DOWNLOAD_URL="https://go.dev/dl/${TARBALL}"

echo "📦 Downloading $TARBALL..."
curl -fsSL "$DOWNLOAD_URL" -o "/tmp/${TARBALL}"

echo "📂 Installing to /usr/local/go..."
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf "/tmp/${TARBALL}"
rm "/tmp/${TARBALL}"

# ---------------------------------------------------------------------------------
# Verify install
# ---------------------------------------------------------------------------------
export PATH=$PATH:/usr/local/go/bin

echo "🔍 Verifying Go install..."
/usr/local/go/bin/go version

# ---------------------------------------------------------------------------------
# Install Go-based CLI tools
# ---------------------------------------------------------------------------------
echo ""
echo "📦 Installing Go-based CLI tools..."

echo "  → gopls"
go install golang.org/x/tools/gopls@latest

echo "  → lazydocker"
go install github.com/jesseduffield/lazydocker@latest

echo "  → lf"
env CGO_ENABLED=0 go install -trimpath -ldflags="-s -w" github.com/gokcehan/lf@latest

echo ""
echo "✅ Golang setup complete."
echo "   Restart your shell or run: source ~/.config/fish/config.fish"

