#!/bin/bash

function usage() {
	cat << END
netctl-auto-ng: An extended automatic wireless management script.

Usage:
	$(basename "$0") [OPTIONS] <target> [interface]

Options:
	-q, --quiet:     Suppress non-error messages.
	--running:       Require the current state to be "running".
	--suspended:     Require the current state to be "suspended" or "running".
	--wpa <fields>:  If target is "status", also print information from
	                 wpa_supplicant (if connected).
	                 If field names are given after "wpa", print them only
	                 (otherwise, print all fields).

States:
	There are three dedicated states of the script/daemon:
	 - running   (scanning is active)
	 - halted    (scanning is stopped, networks are disconnected)
	 - suspended (technically same as halted)

	Their purpose is to allow commands to the script to be skipped
	automatically in a conditional manner (using options described above).

Targets:
	A target is the desired operation mode of the script.
	It may be one of the following:

	continuous:  Scan for networks endlessly, connecting to first found one.

	once:        Scan for networks once (for a timeout), connecting to first
	             found network and stopping as soon as the connection gets lost.

	halt:        Stop the scanner daemon and disconnect from any network.

	suspend:     Same as halt, but go to state "suspended".

	last:        Go to the last active mode (either "continuous" or "once").

	resume:      Equals to "--suspended last".
	             This target is made for readability.

	reconfigure: Equals to "--running last".
	             This target is made for readability (allows to re-read
				 the netctl profile list).

	status:      Print the interface info.

	bootup:      Auto-configure the daemon in a mode acceptable for a
	             system boot sequence (see config).

	power:       Auto-configure the daemon in a mode acceptable for a
	             power source transition (see config).

Interface specification:
    Multiple interfaces may or may not be specified (processed sequentially).
	If not specified, default list is taken.

	Default interfaces:
	- command "halt": all running interfaces
	- other commands: all interfaces

Exit codes:
	0: done or nothing to do
	1: error while processing options or configuration files
	2: unsufficient privileges or locking failed
	3: interface init failed
	4: timeout/abort while waiting for an established connection in "once" mode

Configuration files:
	Native configuration file: /etc/conf.d/netctl-auto-ng
	Network profile directory: /etc/netctl
END
}

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

# Outer routine
#

function outer_routine() {
	local SD_ACTION

	write_runfile_outer
	case "$REQ_MODE" in
		halt|suspend)
			SD_ACTION=stop
			;;
		continuous|once)
			# Actually, all these targets boil down to reading the run-file.
			if systemd_run --quiet is-active; then
				SD_ACTION=reload
			else
				SD_ACTION=start
			fi
			;;
		*)
			quit 1 "Unsupported target \"$REQ_MODE\""
			;;
	esac

	systemd_run "$SD_ACTION" || return

	if ! (( QUIET )) && [[ -t 1 ]]; then
		report_notice "Done \"$SD_ACTION\" for interface \"$INTERFACE\". Current state:"
		systemd_run status -n0
	fi

	return 0
}

# Main execution flow
#

if ! (( "${#INTERFACES[@]}" )); then
	case "$REQ_MODE" in
		halt)
			INTERFACES=( $( list_interfaces_in_state running ) )
			;;
		status|continuous|once|last|suspend|resume|reconfigure)
			INTERFACES=( $( systemd_list_interfaces --all | cut -d' ' -f1 ) )
			;;
	esac
	
	if (( "${#INTEFACES[@]}" )); then
		report_notice "Using default list of interfaces for $REQ_MODE (${INTERFACES[*]})"
	fi
fi

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