#!/bin/bash
set -euo pipefail

VERSION="2.0.0"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
LIB_DIR="$SCRIPT_DIR/lib"

for _lib in colors config detect validate dscl suppress backup status heal firewall harden whitelist check monitor history doctor selfupdate uninstall report ma_detect demo vpn init suggest remediate telemetry predict discord; do
	_lib_path="$LIB_DIR/$_lib.sh"
	if [ -f "$_lib_path" ]; then
		source "$_lib_path"
	else
		echo "ERROR: Library not found: $_lib_path" >&2
		exit 1
	fi
done

show_cmd_help() {
	case "$1" in
		bypass)     echo "Bypass MDM from Recovery. Creates admin user." ;;
		suppress)   echo "Suppress enrollment without creating a user." ;;
		heal)       echo "Re-apply suppression after macOS updates." ;;
		persist)    echo "Install auto-heal LaunchDaemon." ;;
		unpersist)  echo "Remove auto-heal LaunchDaemon." ;;
		firewall)   echo "Block MDM IPs via pf (kernel-level). DoH-proof." ;;
		firewall-off) echo "Remove pf MDM block." ;;
		harden)     echo "Kill MDM processes + remove profiles + flush DNS." ;;
		audit)      echo "Deep system scan with risk score." ;;
		whitelist)  echo "Block only MDM domains, keep iCloud/App Store." ;;
		backup)     echo "Save current state." ;;
		restore)    echo "Restore from backup." ;;
		dualboot)   echo "Target an external macOS install." ;;
		status)     echo "Show MDM enrollment status (Recovery only)." ;;
		check)      echo "Pre-format / pre-upgrade safety report." ;;
		history)    echo "Show event log from monitor/heal runs." ;;
		history-clear) echo "Clear event log." ;;
		monitor)    echo "Start background MDM monitor (5 min interval)." ;;
		monitor-install) echo "Install monitor as LaunchDaemon." ;;
		monitor-uninstall) echo "Remove monitor LaunchDaemon." ;;
		monitor-stop) echo "Stop the monitor daemon." ;;
		monitor-status) echo "Check if monitor is running." ;;
		doctor)     echo "Run pre-flight diagnostics." ;;
		init)       echo "Interactive setup wizard." ;;
		suggest)    echo "Risk-based recommendations." ;;
		remediate)  echo "Per-org MDM cleanup." ;;
		predict)    echo "Look up serial number enrollment." ;;
		telemetry)  echo "Manage anonymous usage stats (opt-in)." ;;
		discord-bot) echo "Start Discord MDM alert bot." ;;
		discord-bot-stop) echo "Stop Discord bot." ;;
		discord-bot-status) echo "Check Discord bot status." ;;
		demo)       echo "Simulated bypass flow (no changes)." ;;
		update)     echo "Self-update from GitHub releases." ;;
		uninstall)  echo "Remove all Unleash traces." ;;
		reinstall)  echo "Uninstall + clean install." ;;
		report)     echo "Generate full status report (markdown or --json)." ;;
		config)     echo "View/edit ~/.unleash.conf settings." ;;
		vpn-kill)   echo "Install pf kill-switch (blocks MDM outside VPN)." ;;
		vpn-kill-remove) echo "Remove VPN kill-switch." ;;
		vpn-kill-status) echo "Check VPN kill-switch status." ;;
		version)    echo "Show version and exit." ;;
		help)       show_help ;;
		*)          show_help ;;
	esac
}

show_help() {
	cat <<'HELP'
Usage: ./unleash <command> [options]

Bypass / suppress / monitor MDM enrollment on macOS.

  COMMANDS

  Core:
    bypass          Full MDM bypass from Recovery (creates admin user)
    suppress        Silence enrollment, no user created
    heal            Check + re-apply suppression after macOS updates

  Persistence:
    persist         Install LaunchDaemon (auto-heal on every boot)
    unpersist       Remove the persistence LaunchDaemon

  Firewall:
    firewall        Block Apple MDM at kernel level via pf
    firewall-off    Remove pf rules
    whitelist       Block only MDM endpoints, keep iCloud/App Store

  Living System:
    harden          Kill MDM processes + remove profiles + flush DNS
    audit           Deep system scan with risk score

  Monitoring:
    check           Pre-format / pre-upgrade safety report
    history         Show event log from monitor/heal runs
    test            Dry-run mode: simulate without changing anything
    monitor         Background daemon (watches MDM every 5 min)
    monitor-install Install monitor as LaunchDaemon (boot persistent)
    monitor-uninstall Remove monitor LaunchDaemon
    monitor-stop    Stop the daemon
    monitor-status  Check if daemon is running

  State:
    backup          Save hosts, profiles, launchd state
    restore         Revert from backup
    dualboot        Target an external macOS install

    init            Interactive setup wizard
    suggest         Risk-based recommendations
    remediate       Per-org MDM cleanup
    predict         Look up serial number enrollment
    telemetry       Manage anonymous usage stats (opt-in)
  Diagnostics:
    doctor          Run pre-flight checks on this environment
    report          Generate a full markdown status report
    history         Show event log from monitor/heal runs
    test            Dry-run mode: simulate without changing anything
    demo            Run simulated bypass flow (no real changes)

  VPN:
    vpn-kill        Install VPN kill-switch (prevents MDM leaks outside VPN)
    vpn-kill-remove Remove VPN kill-switch
    vpn-kill-status Check VPN kill-switch status

  Management:
    config          View/edit persistent settings (~/.unleash.conf)
    update          Self-update to the latest GitHub release
    uninstall       Remove all Unleash traces from the system
    reinstall       Uninstall + reinstall (persist + whitelist + monitor)
    discord-bot         Start Discord MDM alert bot
    discord-bot-stop    Stop Discord bot
    discord-bot-status  Check Discord bot status

  Info:
    status          Show MDM enrollment status (Recovery only)
    version         Show version
    help            This message

ALIASES
    st              status
    ls              status
    fw              firewall
    fw-off          firewall-off
    wl              whitelist
    sv              suppress
    by              bypass
    mn              monitor
    mn-install      monitor-install
    mn-uninstall    monitor-uninstall
    mn-stop         monitor-stop
    mn-st           monitor-status
    doc             doctor
    up              update
    uni             uninstall
    rei             reinstall
    vk              vpn-kill
    vkr             vpn-kill-remove
    vks             vpn-kill-status

OPTIONS
    --verbose       Show debug messages
    --dry-run       Simulate without making changes
    --log-file <f>  Write logs to file (appended)

Run without arguments for interactive menu.
HELP
}

cmd_version() {
	echo "unleash v$VERSION"
	exit 0
}

cmd_bypass() {
	if is_recovery; then
		header "Full MDM Bypass"
		local data_mount
		data_mount=$(resolve_data_volume)
		full_bypass_mode "$data_mount"
	else
		error_exit "Full bypass must run from Recovery mode."
	fi
}

cmd_suppress() {
	header "Suppress Enrollment"
	local data_mount
	data_mount=$(resolve_data_volume)
	suppress_only_mode "$data_mount"
}

cmd_backup() {
	header "Backup"
	local data_mount
	data_mount=$(resolve_data_volume)
	backup_state "$data_mount"
}

cmd_restore() {
	header "Restore"
	restore_state
}

cmd_dualboot() {
	if ! is_root; then
		error_exit "Dual-boot needs sudo: sudo ./unleash dualboot"
	fi

	header "Dual-Boot Mode"

	local volumes
	volumes=$(resolve_target_volumes)
	local sys_path="${volumes%%|*}"
	local data_path="${volumes##*|}"

	info "Target system: $sys_path"
	info "Target data:   $data_path"

	local node
	node=$(dscl_node "$data_path")

	echo ""
	step "Creating admin account on target"

	local realName
	prompt_default realName "Full name" "Apple"
	local username
	prompt_username username
	local passw
	prompt_password passw
	local uid
	uid=$(find_available_uid "$node")

	create_admin_user "$node" "$data_path" "$username" "$realName" "$passw" "$uid"
	touch "$data_path/private/var/db/.AppleSetupDone"

	begin "Blocking domains"
	local hosts_file="$data_path/private/etc/hosts"
	[ -f "$hosts_file" ] || touch "$hosts_file"
	printf '%s\n' "0.0.0.0 deviceenrollment.apple.com" "0.0.0.0 mdmenrollment.apple.com" "0.0.0.0 iprofiles.apple.com" >>"$hosts_file"
	end_ok

	begin "Resetting config profiles"
	local config_path="$data_path/private/var/db/ConfigurationProfiles/Settings"
	mkdir -p "$config_path"
	rm -f "$config_path/.cloudConfigHasActivationRecord" \
	      "$config_path/.cloudConfigRecordFound"
	touch "$config_path/.cloudConfigProfileInstalled" \
	      "$config_path/.cloudConfigRecordNotFound"
	end_ok

	info "User: $username"
	info "Pass: $passw"
	info "Boot the target and login."
}

cmd_heal() {
	if is_recovery; then
		local data_mount
		data_mount=$(resolve_data_volume)
		heal_suppress "$data_mount"
	else
		if ! is_root; then
			error_exit "Heal needs sudo: sudo ./unleash heal"
		fi
		heal_suppress ""
	fi
}

cmd_persist() {
	local data_mount
	if is_recovery; then
		data_mount=$(resolve_data_volume)
	else
		if ! is_root; then
			error_exit "Persistence needs sudo: sudo ./unleash persist"
		fi
		data_mount=""
	fi
	install_persist_launchdaemon "$data_mount"
}

cmd_unpersist() {
	local data_mount
	if is_recovery; then
		data_mount=$(resolve_data_volume)
	else
		data_mount=""
	fi
	remove_persist_launchdaemon "$data_mount"
}

cmd_firewall() {
	if ! is_root; then
		error_exit "Firewall needs sudo: sudo ./unleash firewall"
	fi
	if is_recovery; then
		local data_mount
		data_mount=$(resolve_data_volume)
		install_pf_mdm_block "$data_mount"
	else
		install_pf_mdm_block ""
	fi
}

cmd_firewall_off() {
	if ! is_root; then
		error_exit "Needs sudo: sudo ./unleash firewall-off"
	fi
	if is_recovery; then
		local data_mount
		data_mount=$(resolve_data_volume)
		remove_pf_mdm_block "$data_mount"
	else
		remove_pf_mdm_block ""
	fi
}

cmd_harden() {
	if ! is_root; then
		error_exit "Hardening needs sudo: sudo ./unleash harden"
	fi
	if is_recovery; then
		info "In Recovery — will skip live-OS checks"
	fi
	harden_live_os
}

cmd_audit() {
	if ! is_root; then
		error_exit "Audit needs sudo: sudo ./unleash audit"
	fi
	deep_status
}

cmd_whitelist() {
	if ! is_root; then
		error_exit "Whitelist needs sudo: sudo ./unleash whitelist"
	fi
	if is_recovery; then
		local data_mount
		data_mount=$(resolve_data_volume)
		install_selective_block "$data_mount"
	else
		install_selective_block ""
	fi
}

cmd_status() {
	if is_recovery; then
		local data_mount
		data_mount=$(resolve_data_volume)
		check_mdm_status "$data_mount"
	else
		error_exit "Status works from Recovery. Try 'check' or 'audit' instead."
	fi
}

cmd_check() {
  if ! is_root; then
    error_exit "Check needs sudo: sudo ./unleash check"
  fi
  run_preformat_check
  echo ""
  check_upgrade_safety
}

cmd_monitor() {
  local webhook=""
  local args=()
  while [ $# -gt 0 ]; do
    case "$1" in
      install|uninstall) args+=("$1"); shift ;;
      --webhook) webhook="$2"; shift 2 ;;
      *) args+=("$1"); shift ;;
    esac
  done
  set -- "${args[@]}"
  if [ -n "$webhook" ]; then
    DISCORD_WEBHOOK="$webhook"
  fi
  case "${1:-}" in
    install)   install_monitor_launchdaemon "" ;;
    uninstall) uninstall_monitor_launchdaemon "" ;;
    *)         monitor_mdm ;;
  esac
}

cmd_monitor_stop() { stop_monitor; }
cmd_monitor_status() { monitor_status; }
cmd_history() { show_history; }
cmd_history_clear() { clear_history; }
cmd_test() {
  header "Dry Run Mode"
  DRY_RUN=true
  local cmd="${2:-suppress}"
  case "$cmd" in
    bypass)    info "Simulating: bypass";   cmd_bypass ;;
    suppress)  info "Simulating: suppress"; cmd_suppress ;;
    heal)      info "Simulating: heal";     cmd_heal ;;
    harden)    info "Simulating: harden";   cmd_harden ;;
    firewall)  info "Simulating: firewall"; cmd_firewall ;;
    whitelist) info "Simulating: whitelist"; cmd_whitelist ;;
    all)
      info "Simulating all available operations..."
      info ""
      DRY_RUN=true suppress_enrollment "/"
      info ""
      DRY_RUN=true full_bypass_mode "/"
      info ""
      info "Dry-run complete. No changes were made."
      ;;
    *) info "Usage: ./unleash test {bypass|suppress|heal|harden|firewall|whitelist|all}" ;;
  esac
}

cmd_interactive_recovery() {
	header "unleash"

	local data_mount
	data_mount=$(resolve_data_volume)
	echo ""

	PS3="Choose: "
	local options=(
		"Full bypass (create admin + suppress MDM)"
		"Suppress enrollment only"
		"Auto-heal"
		"Install pf firewall"
		"Remove pf firewall"
		"Install selective block (iCloud-safe)"
		"Live-OS harden"
		"Deep MDM audit"
		"Backup state"
		"Restore from backup"
		"Check MDM status"
		"Pre-format check"
		"Reboot"
		"Exit"
	)
	select opt in "${options[@]}"; do
		case $opt in
			"Full bypass (create admin + suppress MDM)")
				full_bypass_mode "$data_mount"
				info "Reboot to apply."
				;;
			"Suppress enrollment only")
				suppress_only_mode "$data_mount"
				;;
			"Auto-heal")
				heal_suppress "$data_mount"
				;;
			"Install pf firewall")
				install_pf_mdm_block "$data_mount"
				;;
			"Remove pf firewall")
				remove_pf_mdm_block "$data_mount"
				;;
			"Install selective block (iCloud-safe)")
				install_selective_block "$data_mount"
				;;
			"Live-OS harden")
				harden_live_os
				;;
			"Deep MDM audit")
				deep_status
				;;
			"Backup state")
				backup_state "$data_mount"
				;;
			"Restore from backup")
				restore_state
				;;
			"Check MDM status")
				check_mdm_status "$data_mount"
				;;
			"Pre-format check")
				run_preformat_check
				;;
			"Reboot")
				info "Rebooting..."
				reboot
				;;
			"Exit")
				exit 0
				;;
			*)
				echo -e "${RED}Invalid option $REPLY${NC}"
				;;
		esac
	done
}

cmd_interactive_normal() {
	header "unleash"
	echo -e "${YEL}Not in Recovery. Limited options.${NC}"
	echo "  Try: sudo ./unleash heal | harden | audit | check | monitor"
	echo ""

	PS3="Choose: "
	local options=(
		"Auto-heal"
		"Backup state"
		"Restore from backup"
		"Exit"
	)
	select opt in "${options[@]}"; do
		case $opt in
		"Auto-heal")
			if ! is_root; then
				error_exit "Heal needs sudo. Run: sudo ./unleash"
			fi
			heal_suppress ""
			;;
		"Backup state")
			local data_mount
			data_mount=$(resolve_data_volume)
			backup_state "$data_mount"
			;;
		"Restore from backup")
			restore_state
			;;
		"Exit")
			exit 0
			;;
		*)
			echo -e "${RED}Invalid $REPLY${NC}"
			;;
		esac
	done
}

parse_global_opts() {
	local args=()
	while [ $# -gt 0 ]; do
		case "$1" in
			--verbose) VERBOSE=true; shift ;;
			--dry-run) DRY_RUN=true; shift ;;
			--log-file) LOG_FILE="$2"; shift 2 ;;
			*) args+=("$1"); shift ;;
		esac
	done
	set -- "${args[@]}"
	echo "$@"
}

main() {
	load_config
	eval "set -- $(parse_global_opts "$@")"

	# Per-command help
	if [ "${2:-}" = "--help" ] || [ "${2:-}" = "-h" ]; then
		show_cmd_help "${1:-}"
		exit 0
	fi

	case "${1:-}" in
		bypass|by)       cmd_bypass ;;
		suppress|sv)     cmd_suppress ;;
		heal)             cmd_heal ;;
		persist)          cmd_persist ;;
		unpersist)        cmd_unpersist ;;
		firewall|fw)      cmd_firewall ;;
		firewall-off|fw-off) cmd_firewall_off ;;
		harden)           cmd_harden ;;
		audit)            cmd_audit "$2" ;;
		whitelist|wl)     cmd_whitelist ;;
		backup)           cmd_backup ;;
		restore)          cmd_restore ;;
		dualboot)         cmd_dualboot ;;
		status|st|ls)     cmd_status ;;
		check)            cmd_check ;;
		history)          cmd_history ;;
		history-clear)    cmd_history_clear ;;
		test|dry-run)     cmd_test "$@" ;;
		monitor|mn)           cmd_monitor "$@" ;;
		monitor-install|mn-install) install_monitor_launchdaemon "" ;;
		monitor-uninstall|mn-uninstall) uninstall_monitor_launchdaemon "" ;;
		monitor-stop|mn-stop) cmd_monitor_stop ;;
		monitor-status|mn-st) cmd_monitor_status ;;
		version|-v|--version) cmd_version ;;
		init)            cmd_init ;;
		suggest)         cmd_suggest ;;
		remediate)       cmd_remediate "$2" ;;
		predict)         cmd_predict "$2" ;;
		telemetry)       telemetry_opt_in "$2" ;;
		demo)             run_demo ;;
		update)           do_self_update ;;
		uninstall)        do_uninstall ;;
		report)           generate_report "$2" ;;
		config)           cmd_config "$@" ;;
		vpn-kill)         vpn_kill_install "$@" ;;
		vpn-kill-remove)  vpn_kill_remove ;;
		vpn-kill-status)  vpn_kill_status ;;
		reinstall)
			do_uninstall
			install_persist_launchdaemon ""
			install_selective_block ""
			install_monitor_launchdaemon ""
			success "Reinstall complete"
			;;
		discord-bot)          cmd_discord_bot_install "$2" "$3" ;;
		discord-bot-stop)     cmd_discord_bot_stop ;;
		discord-bot-status)   cmd_discord_bot_status ;;
		help|-h|--help)   show_help; exit 0 ;;
		"")
			if is_recovery; then
				cmd_interactive_recovery
			else
				cmd_interactive_normal
			fi
			;;
		*)
			echo -e "${RED}Unknown: $1${NC}" >&2
			show_help >&2
			exit 1
			;;
	esac
}

main "$@"
