#!/bin/sh
# xwire installer — audit me: https://xwire.hkroot.de/install.sh
set -eu

BASE=${XWIRE_BASE:-https://xwire.hkroot.de}
BINS="xshare xcast xwire xwire-list xwire-monitors xwire-rewire xwire-daemon xwire-remote xwire-install"
SHARE=${XDG_DATA_HOME:-$HOME/.local/share}/xwire

fetch() { curl -fsSL "$1" -o "$2" 2>/dev/null || wget -qO "$2" "$1"; }

# Deno runs the tools from source (~1 MB) — reuse a current install, else install it.
if ! command -v deno >/dev/null 2>&1; then
  echo "xwire: installing Deno to ~/.deno/bin"
  fetch https://deno.land/install.sh - | sh -s -- -y
  PATH="$HOME/.deno/bin:$PATH"
fi
ver=$(deno --version | awk 'NR==1{print $2}')
[ "${ver%%.*}" -ge 2 ] || { echo "xwire: deno $ver is too old (need 2.x)" >&2; exit 1; }

# Where to install: reuse the directory of an existing install, else ask.
dir=""
for d in "$HOME/.local/bin" /usr/local/bin /usr/bin; do
  if [ -x "$d/xwire" ]; then dir=$d; break; fi
done
if [ -z "$dir" ]; then
  printf 'Install xwire to:\n  1) %s/.local/bin (user)\n  2) /usr/local/bin (sudo)\n  3) /usr/bin (sudo)\nChoice [1]: ' "$HOME"
  read -r choice </dev/tty || choice=1
  case ${choice:-1} in
    2) dir=/usr/local/bin ;;
    3) dir=/usr/bin ;;
    *) dir=$HOME/.local/bin ;;
  esac
fi

# sudo only when we are not root and the target is not writable.
sudo=""
if [ "$(id -u)" -ne 0 ] && [ ! -w "$dir" ]; then sudo=sudo; fi

echo "xwire: deno $ver · source → $SHARE · bin → $dir"
mkdir -p "$SHARE"
$sudo mkdir -p "$dir"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
fetch "$BASE/release/xwire-src.tar.gz" "$tmp/src.tgz"
tar -xzf "$tmp/src.tgz" -C "$SHARE"
for b in $BINS; do
  printf '#!/bin/sh\nexec deno run -A --config "%s/deno.json" "%s/src/bin/%s.ts" "$@"\n' \
    "$SHARE" "$SHARE" "$b" > "$tmp/$b"
  chmod 0755 "$tmp/$b"
  $sudo install -m 0755 "$tmp/$b" "$dir/$b"
done
echo "xwire installed to $dir — make sure it is on your PATH."
