#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT_DIR"

INSTALL_ROOT="${RHO_INSTALL_ROOT:-}"
OFFLINE="${RHO_INSTALL_OFFLINE:-0}"
CARGO_BIN_DIR="${CARGO_HOME:-$HOME/.cargo}/bin"

usage() {
  cat <<EOF
usage: ./install.sh [--root <dir>] [--offline]

Build and install the Rho CLI binary with Cargo.

Defaults:
  cargo install --path . --bin rho --locked --force

Options:
  --root <dir>   Install under <dir>/bin instead of Cargo's default bin dir.
  --offline      Install without accessing the network; requires cached crates.

Environment:
  RHO_INSTALL_ROOT   Same as --root.
  RHO_INSTALL_OFFLINE=1
                     Same as --offline.
  CARGO_HOME         Cargo home; default is ~/.cargo.
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --root)
      [[ $# -ge 2 ]] || { echo "missing value after --root" >&2; exit 2; }
      INSTALL_ROOT="$2"
      shift 2
      ;;
    --offline)
      OFFLINE=1
      shift
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    *)
      echo "unknown argument: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

cargo_args=(install --path "$ROOT_DIR" --bin rho --locked --force)
if [[ "$OFFLINE" == "1" ]]; then
  cargo_args+=(--offline)
fi

if [[ -n "$INSTALL_ROOT" ]]; then
  mkdir -p "$INSTALL_ROOT"
  cargo "${cargo_args[@]}" --root "$INSTALL_ROOT"
  BIN_DIR="$INSTALL_ROOT/bin"
else
  cargo "${cargo_args[@]}"
  BIN_DIR="$CARGO_BIN_DIR"
fi

echo
echo "Rho installed to: $BIN_DIR"
echo
echo "Installed binary:"
if [[ -x "$BIN_DIR/rho" ]]; then
  echo "  $BIN_DIR/rho"
else
  echo "  missing: $BIN_DIR/rho" >&2
  exit 1
fi

echo
if command -v rho >/dev/null 2>&1 && [[ "$(command -v rho)" == "$BIN_DIR/rho" ]]; then
  echo "rho is already first on PATH:"
  echo "  $(command -v rho)"
else
  echo "Add this to your shell profile if it is not already on PATH:"
  echo "  export PATH=\"$BIN_DIR:\$PATH\""
fi

echo
echo "Smoke check:"
"$BIN_DIR/rho" --version >/dev/null || {
  echo "rho --version failed" >&2
  exit 1
}
echo "  $("$BIN_DIR/rho" --version)"
