#!/bin/bash

INNER=1

. /usr/lib/network/auto-ng.functions

# Inner routine
#

function inner_routine() {
	rm -f "$HALT_SCRIPT"

	case "$REQ_MODE" in
		halt)
			stop
			echo "halted" > "$STATE_FILE"
			quit 0 "Successfully halted"
			;;
		suspend)
			stop
			echo "suspended" > "$STATE_FILE"
			quit 0 "Successfully suspended"
			;;
		continuous|once)
			[[ "$STATE" != "running" ]] && ( release_lock; start; ) || reconfigure
			echo "running" > "$STATE_FILE"
			echo "$REQ_MODE" > "$MODE_FILE"
			if [[ "$REQ_MODE" = "once" ]]; then
	#			(

				: ${NAW_ONCE_TIMEOUT:=10}
				: ${NAW_STATE_ONCE_FAULT:=suspended}

				function onexit() {
					stop
					echo "$NAW_STATE_ONCE_FAULT" > "$STATE_FILE"
					quit 4 "Failed waiting for a connection"
				}
				do_trap onexit
				report_debug "Entering once mode: waiting for connection on $INTERFACE for $NAW_ONCE_TIMEOUT seconds"
				if wpa_wait_until_state "$NAW_ONCE_TIMEOUT" "$INTERFACE" "COMPLETED"; then
					local LOSS_CMD="$(get_cmd_from_config ONCE_LOSS)"
					[[ "$LOSS_CMD" ]] && echo "\"$(realpath "$0")\" $LOSS_CMD" > "$HALT_SCRIPT"
				else
					onexit
				fi
	#			) &
			fi
			quit 0 "Running $REQ_MODE"
			;;
		*)
			quit 1 "Unsupported target \"$REQ_MODE\""
			;;
	esac

	quit 1 "Something wrong with the inner level"
}

# Main execution flow
#

for interface in "${INTERFACES[@]}"; do
	(
	load_interface "$interface"
	inner_routine
	) || exit $?
done
