#!/usr/bin/env sh
set -eu
HUB="${TEMP_REMOTE_TOOL_HUB:-https://down.luckyfound.info}"
TOKEN="${TEMP_REMOTE_TOOL_AGENT_TOKEN:-}"
WORK="${TEMP_REMOTE_TOOL_HOME:-$HOME/.temporary_remote_tool/go}"
if [ -z "$TOKEN" ]; then echo "TEMP_REMOTE_TOOL_AGENT_TOKEN required" >&2; exit 2; fi
OS="$(uname -s | tr 'A-Z' 'a-z')"
case "$OS" in linux*) OS=linux;; darwin*) OS=darwin;; *) echo "unsupported os $OS" >&2; exit 2;; esac
ARCH="$(uname -m)"
case "$ARCH" in x86_64|amd64) ARCH=amd64;; aarch64|arm64) ARCH=arm64;; *) echo "unsupported arch $ARCH" >&2; exit 2;; esac
mkdir -p "$WORK"
BIN="$WORK/temporary-remote-tool"
URL="$HUB/install/bin/go/$OS/$ARCH"
export TEMP_REMOTE_TOOL_HUB="$HUB"
export TEMP_REMOTE_TOOL_AGENT_TOKEN="$TOKEN"
download() {
  if command -v curl >/dev/null 2>&1; then curl -fsSL "$URL" -o "$BIN"; return $?; fi
  if command -v wget >/dev/null 2>&1; then wget -qO "$BIN" "$URL"; return $?; fi
  if command -v python3 >/dev/null 2>&1; then python3 - "$URL" "$BIN" <<'PY'
import sys, urllib.request
urllib.request.urlretrieve(sys.argv[1], sys.argv[2])
PY
    return $?
  fi
  return 1
}
if download; then
  chmod +x "$BIN"
  exec "$BIN" agent
fi
if ! command -v go >/dev/null 2>&1; then echo "no prebuilt binary and go not installed" >&2; exit 2; fi
SRC="$WORK/src"
ZIP="$WORK/go.zip"
if command -v curl >/dev/null 2>&1; then curl -fsSL "$HUB/install/archive/go.zip" -o "$ZIP"; else wget -qO "$ZIP" "$HUB/install/archive/go.zip"; fi
rm -rf "$SRC"; mkdir -p "$SRC"
python3 - "$ZIP" "$SRC" <<'PY'
import sys, zipfile
with zipfile.ZipFile(sys.argv[1]) as z:
    z.extractall(sys.argv[2])
PY
(cd "$SRC/go_client" && go build -o "$BIN" .)
exec "$BIN" agent
