#!/usr/bin/env bash
# Wrapper so the toolkit can be started from a shell without typing pwsh first.
#   intune                          interactive launcher (Start-IntuneToolkit.ps1)
#   intune -TenantId <id> ...       launcher with parameters
#   intune <Script> [args]          run Scripts/<Script>.ps1 or .py, e.g.
#                                   intune Export-Policies -TenantId <id> -ExportPath ~/out
#                                   intune Compare-Tenants --root-a A --root-b B
# Symlink it onto your PATH:  ln -s "$PWD/intune" ~/.local/bin/intune
set -euo pipefail

src="${BASH_SOURCE[0]}"
while [ -L "$src" ]; do
  dir="$(cd -P "$(dirname "$src")" && pwd)"
  src="$(readlink "$src")"
  [[ "$src" != /* ]] && src="$dir/$src"
done
root="$(cd -P "$(dirname "$src")" && pwd)"

need() { command -v "$1" >/dev/null 2>&1 || { echo "intune: '$1' not found. $2" >&2; exit 127; }; }

if [ $# -gt 0 ] && [[ "$1" != -* ]]; then
  name="${1%.ps1}"; name="${name%.py}"; shift
  if [ -f "$root/Scripts/$name.py" ]; then
    need python3 "Install Python 3."
    exec python3 "$root/Scripts/$name.py" "$@"
  elif [ -f "$root/Scripts/$name.ps1" ]; then
    need pwsh "Install PowerShell 7: brew install powershell"
    exec pwsh -NoProfile -File "$root/Scripts/$name.ps1" "$@"
  fi
  echo "intune: no script 'Scripts/$name.ps1' or '.py'. Available:" >&2
  ls "$root/Scripts" | grep -E '\.(ps1|py)$' | grep -v '^_' | sed -E 's/\.(ps1|py)$//' | sort -u | sed 's/^/  /' >&2
  exit 2
fi

need pwsh "Install PowerShell 7: brew install powershell"
exec pwsh -NoProfile -File "$root/Start-IntuneToolkit.ps1" "$@"
