#!/bin/sh
# The az a woken session finds first:  it refuses to run without the session's
# own Azure config directory (k-2026-0929-az-default-config-fallback).
#
# The Azure CLI reads `AZURE_CONFIG_DIR or ~/.azure`, so a session whose
# variable was lost to a subshell or a wrapper silently runs as whatever is
# signed in at the machine's default directory, which is a person's login.  The
# spawner always sets the variable;  this makes its absence a refusal instead
# of a fallback.  This directory is on a woken session's PATH only, so a
# person's own shell never meets it.
#
# Refused:  AZURE_CONFIG_DIR unset, empty, or naming the default directory.
# Otherwise the next az on PATH runs with the arguments unchanged.

refuse() {
  echo "az refused:  $1.  A woken session uses its own Azure config directory" \
       "and never the machine's default ~/.azure, which belongs to a person." \
       "Run az from the session's own environment, where AZURE_CONFIG_DIR is set." >&2
  exit 78
}

dir="${AZURE_CONFIG_DIR:-}"
[ -n "$dir" ] || refuse "AZURE_CONFIG_DIR is not set"

trim() {
  t="$1"
  while [ "${#t}" -gt 1 ] && [ "${t%/}" != "$t" ]; do t="${t%/}"; done
  printf '%s' "$t"
}
dir="$(trim "$dir")"

# The default, compared as a path string.  HOME is resolved and the directory
# itself is never opened, so the check reads nothing of a person's login.
for home in "${HOME:-}" "$(eval echo "~$(id -un 2>/dev/null)" 2>/dev/null)"; do
  [ -n "$home" ] || continue
  home="$(trim "$home")"
  [ "$dir" = "$home/.azure" ] && refuse "AZURE_CONFIG_DIR names the default directory"
  real_home="$(cd "$home" 2>/dev/null && pwd -P)" || continue
  [ "$dir" = "$real_home/.azure" ] && refuse "AZURE_CONFIG_DIR names the default directory"
  if real_dir="$(cd "$dir" 2>/dev/null && pwd -P)"; then
    [ "$real_dir" = "$real_home/.azure" ] && refuse "AZURE_CONFIG_DIR names the default directory"
  fi
done

here="$(cd "$(dirname "$0")" && pwd -P)"
IFS=:
for p in $PATH; do
  [ -n "$p" ] || continue
  rp="$(cd "$p" 2>/dev/null && pwd -P)" || continue
  [ "$rp" = "$here" ] && continue
  if [ -f "$p/az" ] && [ -x "$p/az" ]; then
    exec "$p/az" "$@"
  fi
done
echo "az:  not found on PATH" >&2
exit 127
