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

REAL_HELPER="/usr/local/lib/solar-desktop/devra-provision"

die() {
  echo "$*" >&2
  exit 1
}

desktop_user="${SUDO_USER:-}"
if [[ -z "$desktop_user" || "$desktop_user" == "root" ]]; then
  die "SolaR Desktop provision must be executed through sudo by the desktop user."
fi

if ! [[ "$desktop_user" =~ ^[a-z_][a-z0-9_-]{1,31}$ ]]; then
  die "Invalid desktop user."
fi

desktop_home="$(getent passwd "$desktop_user" | cut -d: -f6)"
[[ -n "$desktop_home" && -d "$desktop_home" ]] || die "Desktop user home not found."

data_root="$desktop_home/.local/share/solar-desktop"
r_root="$data_root/R"
python_runtime_root="$data_root/python-runtimes"
python_env_root="$data_root/python-envs"

[[ -x "$REAL_HELPER" ]] || die "Internal provision helper is not installed."

case "${1:-}" in
  install-r)
    [[ $# -eq 3 ]] || die "Usage: install-r VERSION R_ROOT"
    [[ "$3" == "$r_root" ]] || die "R root is not allowed for SolaR Desktop."
    exec "$REAL_HELPER" "$@"
    ;;
  install-python)
    [[ $# -eq 3 ]] || die "Usage: install-python VERSION PYTHON_RUNTIME_ROOT"
    [[ "$3" == "$python_runtime_root" ]] || die "Python runtime root is not allowed for SolaR Desktop."
    exec "$REAL_HELPER" "$@"
    ;;
  install-system-deps)
    [[ $# -ge 2 ]] || die "Usage: install-system-deps DEPENDENCY [...]"
    exec "$REAL_HELPER" "$@"
    ;;
  repair-python-env)
    [[ $# -eq 4 ]] || die "Usage: repair-python-env PATH OWNER GROUP"
    case "$2" in
      "$python_env_root"|"$python_env_root"/*) ;;
      *) die "Python environment path is not allowed for SolaR Desktop." ;;
    esac
    [[ "$3" == "$desktop_user" ]] || die "Python environment owner is not allowed."
    exec "$REAL_HELPER" "$@"
    ;;
  *)
    die "Command not supported in SolaR Desktop."
    ;;
esac
