#!/bin/sh

. ${CIRROS_LIB:=/lib/cirros/shlib_cirros} ||
	{ echo "failed to read ${CIRROS_LIB}" 1>&2; exit 1; }

Usage() {
	cat <<EOF
Usage: ${0##*/} [ options ]

   output status of the system.
   Normally this would be used for debugging, or to console
   to show user information.

   options:
   -v | --verbose  : be more verbose
EOF
}

cleanup() {
	[ -z "${TEMP_D}" -o ! -d "${TEMP_D}" ] || rm -Rf "${TEMP_D}"
}

cirros_status() {
	local short_opts="hv"
	local long_opts="help,verbose"
	local getopt_out=""
	getopt_out=$(getopt --name "${0##*/}" \
		--options "${short_opts}" --long "${long_opts}" -- "$@") &&
		eval set -- "${getopt_out}" ||
		{ bad_Usage; return; }

	local cur="" next="" mode="" VERBOSITY

	while [ $# -ne 0 ]; do
		cur=${1}; next=${2};
		case "$cur" in
			-h|--help) Usage ; exit 0;;
			-v|--verbose) VERBOSITY=$((${VERBOSITY}+1));;
			--) shift; break;;
		esac
		shift;
	done

	[ $# -eq 0 ] || { bad_Usage "no arguments expected"; return; }

	TEMP_D=$(mktemp -d "${TMPDIR:-/tmp}/${0##*/}.XXXXXX") ||
		{ error "failed to make tempdir"; return 1; }
	trap cleanup EXIT

	local oifs="$IFS" x="" val=""
	echo "=== network info ==="
	ip addr show > "$TEMP_D/ip-addr-show"
	ipinfo < "$TEMP_D/ip-addr-show"
	IFS="|"; set -- $_RET; IFS="$oifs"
	for x in "$@"; do
		echo "if-info: $x"
	done
	ip route | sed 's,^,ip-route:,'

	if assert_datasource; then
		echo "=== datasource: $_DATASOURCE_NAME $_DATASOURCE_MODE ==="
		for x in instance-id name availability-zone local-hostname \
		         launch-index; do
			ds_get_item "$x" && val="$_RET" || val="N/A"
			echo "$x: ${val}"
		done
	else
		echo "=== datasource: None None ==="
	fi

	local cur="" avail="" msg=""
	cirros_version_available && avail="$_RET"
	cirros_version && cur="$_RET"
	msg="current=$cur"
	[ "$avail" != "0.0" ] && msg="$msg latest=$avail"

	read_uptime && [ -n "$_RET" ] && msg="$msg uptime=$_RET"
	echo "=== cirros: $msg ==="

	if ! check_ping_gateway; then
		echo "=== pinging gateway failed, debugging connection ==="
 		debug_connection
	fi

	return 0
}

cirros_status "$@"

# vi: ts=4 noexpandtab
