#!/bin/bash
# Go Overlay
# Adds: Go toolchain
#
# Usage: Called by dev.sh during container creation
#   apply_go_overlay <container_name>

set -e

OVERLAY_NAME="go"

# Go version to install
GO_VERSION="1.22.0"

apply_go_overlay() {
    local container="$1"

    echo "[OVERLAY] Applying Go overlay to $container..."

    sudo machinectl shell "$container" /bin/bash -c '
# Download and install Go
GO_VERSION="1.22.0"
curl -LO "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz"
rm -rf /usr/local/go
tar -C /usr/local -xzf "go${GO_VERSION}.linux-amd64.tar.gz"
rm "go${GO_VERSION}.linux-amd64.tar.gz"

# Add to system profile
echo '\''export PATH=$PATH:/usr/local/go/bin'\'' > /etc/profile.d/go.sh
chmod +x /etc/profile.d/go.sh

# Setup GOPATH for dev user
su - dev -c "mkdir -p ~/go/{bin,src,pkg}"
echo '\''export GOPATH=$HOME/go'\'' >> /home/dev/.bashrc
echo '\''export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin'\'' >> /home/dev/.bashrc

# Install common Go tools
su - dev -c "export PATH=$PATH:/usr/local/go/bin && go install golang.org/x/tools/gopls@latest"
su - dev -c "export PATH=$PATH:/usr/local/go/bin && go install github.com/go-delve/delve/cmd/dlv@latest"

# Verify
/usr/local/go/bin/go version
'

    echo "[OVERLAY] Go overlay applied"
}

# Allow sourcing or direct execution
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    if [ -z "$1" ]; then
        echo "Usage: $0 <container_name>"
        exit 1
    fi
    apply_go_overlay "$1"
fi
