#!/usr/bin/env bash

BOOTSTRAP_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

# shellcheck source=lib/log.sh
source "$BOOTSTRAP_ROOT/lib/log.sh"
# shellcheck source=lib/ui.sh
source "$BOOTSTRAP_ROOT/lib/ui.sh"
# shellcheck source=lib/system.sh
source "$BOOTSTRAP_ROOT/lib/system.sh"
# shellcheck source=lib/network.sh
source "$BOOTSTRAP_ROOT/lib/network.sh"
# shellcheck source=lib/prompts.sh
source "$BOOTSTRAP_ROOT/lib/prompts.sh"
# shellcheck source=lib/validation.sh
source "$BOOTSTRAP_ROOT/lib/validation.sh"
# shellcheck source=core/runtime.sh
source "$BOOTSTRAP_ROOT/core/runtime.sh"
# shellcheck source=core/registry.sh
source "$BOOTSTRAP_ROOT/core/registry.sh"
# shellcheck source=core/dispatcher.sh
source "$BOOTSTRAP_ROOT/core/dispatcher.sh"
# shellcheck source=core/test_runner.sh
source "$BOOTSTRAP_ROOT/core/test_runner.sh"
# shellcheck source=menus/main.sh
source "$BOOTSTRAP_ROOT/menus/main.sh"

bootstrap_parse_args() {
  BOOTSTRAP_MODE="menu"
  BOOTSTRAP_MODULE_ID=""
  BOOTSTRAP_TARGET_USER=""

  while [[ $# -gt 0 ]]; do
    case "$1" in
      --module)
        BOOTSTRAP_MODE="module"
        BOOTSTRAP_MODULE_ID="${2:-}"
        shift 2
        ;;
      --user)
        BOOTSTRAP_TARGET_USER="${2:-}"
        shift 2
        ;;
      --help|-h)
        BOOTSTRAP_MODE="help"
        shift
        ;;
      *)
        ui_error "Argument non reconnu : $1"
        return 1
        ;;
    esac
  done

  if [[ "$BOOTSTRAP_MODE" == "module" && -z "$BOOTSTRAP_MODULE_ID" ]]; then
    ui_error "Option --module incomplete"
    return 1
  fi
}

bootstrap_print_help() {
  cat <<'EOF'
Usage:
  bash install.sh
  bash install.sh --module <module-id> [--user <username>]

Exemples:
  bash install.sh --module system/user-sudo
  bash install.sh --module system/user-sudo --user gilles
EOF
}

bootstrap_run() {
  bootstrap_parse_args "$@" || exit 1

  runtime_init "$BOOTSTRAP_ROOT"
  log_init

  ui_header "Postinstall Debian"
  ui_info "Initialisation du framework"

  system_require_bash
  system_require_debian
  system_require_root
  network_warn_if_offline

  registry_init

  case "$BOOTSTRAP_MODE" in
    help)
      bootstrap_print_help
      ;;
    module)
      dispatcher_run_module "$BOOTSTRAP_MODULE_ID" "$BOOTSTRAP_TARGET_USER"
      ;;
    *)
      menu_main
      ;;
  esac
}
