#!/bin/sh
# Bootstrap for `curl -fsSL https://get.deql.osm-data.com | sh`.
#
# Downloads the small deql-init onboarding binary and hands over to it. The main
# deql binary is downloaded by deql-init itself, once it knows what you want.
set -eu

BASE="${DEQL_RELEASE_BASE:-https://downloads.deql.osm-data.com}"

os=$(uname -s)
arch=$(uname -m)

case "$os-$arch" in
  Linux-x86_64)   target=x86_64-unknown-linux-musl ;;
  Linux-aarch64)  target=aarch64-unknown-linux-musl ;;
  Linux-arm64)    target=aarch64-unknown-linux-musl ;;
  Darwin-x86_64)  target=x86_64-apple-darwin ;;
  Darwin-arm64)   target=aarch64-apple-darwin ;;
  *)
    echo "deql: no prebuilt binary for $os $arch" >&2
    echo "Build from source: https://github.com/osm-data/DeQL" >&2
    exit 1
    ;;
esac

tmp=$(mktemp -d "${TMPDIR:-/tmp}/deql-init.XXXXXX")
# Not exec'd below, so this still runs once the user leaves the deql shell.
trap 'rm -rf "$tmp"' EXIT INT TERM

echo "Fetching the DeQL installer for $target..."
if command -v curl >/dev/null 2>&1; then
  curl -fsSL "$BASE/deql-init-$target" -o "$tmp/deql-init"
elif command -v wget >/dev/null 2>&1; then
  wget -qO "$tmp/deql-init" "$BASE/deql-init-$target"
else
  echo "deql: neither curl nor wget is available" >&2
  exit 1
fi
chmod +x "$tmp/deql-init"

# Piping this script into sh leaves stdin on the pipe; the TUI needs the terminal.
if [ -t 0 ]; then
  "$tmp/deql-init"
# Not `[ -e /dev/tty ]`: the node exists on any Linux, but opening it fails with
# ENXIO when the process has no controlling terminal, which is the real question.
elif (: < /dev/tty) 2>/dev/null; then
  "$tmp/deql-init" < /dev/tty
else
  echo "deql: no terminal available — download deql-init and run it directly" >&2
  exit 1
fi
