#!/bin/sh
# WorkTracker wt-client installer — https://time.itcm.se/download
#
# Detects OS and architecture, downloads the wt-client binary currently
# served in production, verifies its checksum and installs it on the PATH
# as `wt-client`. Linux and macOS only; Windows users download the .exe
# from the download page instead.
#
#   curl -fsSL https://time.itcm.se/install.sh | sh
#
# Override the install directory with WT_INSTALL_DIR, the site with WT_BASE_URL.
set -eu

BASE_URL="${WT_BASE_URL:-https://time.itcm.se}"

os=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$os" in
  linux | darwin) ;;
  *)
    echo "install.sh supports Linux and macOS. On Windows, download wt-client-windows-amd64.exe from $BASE_URL/download" >&2
    exit 1
    ;;
esac

arch=$(uname -m)
case "$arch" in
  x86_64 | amd64) arch=amd64 ;;
  aarch64 | arm64) arch=arm64 ;;
  *)
    echo "unsupported architecture: $arch (wt-client is built for amd64 and arm64)" >&2
    exit 1
    ;;
esac

file="wt-client-$os-$arch"
url="$BASE_URL/downloads/$file"

tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT INT TERM

echo "downloading $url"
curl -fsSL "$url" -o "$tmpdir/wt-client"

# Verify against the checksums published next to the binaries.
if command -v sha256sum >/dev/null 2>&1; then
  sum() { sha256sum "$1" | cut -d' ' -f1; }
elif command -v shasum >/dev/null 2>&1; then
  sum() { shasum -a 256 "$1" | cut -d' ' -f1; }
else
  sum() { :; }
  echo "warning: no sha256sum/shasum found, skipping checksum verification" >&2
fi
expected=$(curl -fsSL "$BASE_URL/downloads/SHA256SUMS" | grep " $file\$" | cut -d' ' -f1 || true)
actual=$(sum "$tmpdir/wt-client")
if [ -n "$actual" ]; then
  if [ -z "$expected" ]; then
    echo "warning: $file not found in SHA256SUMS, skipping checksum verification" >&2
  elif [ "$actual" != "$expected" ]; then
    echo "checksum mismatch for $file: expected $expected, got $actual" >&2
    exit 1
  else
    echo "checksum verified"
  fi
fi

chmod +x "$tmpdir/wt-client"

# Pick the install directory: an explicit override, /usr/local/bin when
# writable, ~/.local/bin otherwise.
if [ -n "${WT_INSTALL_DIR:-}" ]; then
  dir="$WT_INSTALL_DIR"
elif [ -w /usr/local/bin ]; then
  dir=/usr/local/bin
else
  dir="$HOME/.local/bin"
fi
mkdir -p "$dir"
mv "$tmpdir/wt-client" "$dir/wt-client"

version=$("$dir/wt-client" version 2>/dev/null || true)
echo "installed ${version:-wt-client} to $dir/wt-client"
case ":$PATH:" in
  *":$dir:"*) ;;
  *) echo "note: $dir is not on your PATH — add it, or move the binary somewhere that is" ;;
esac
echo "next: create an agent token in WorkTracker (Profile -> Agent access), then run: wt-client setup"
