#!/bin/bash display_help() { >&2 printf 'lights-out version #VERSION#\n' >&2 printf '\n' >&2 printf 'usage:\n' >&2 printf ' lights-out get $input: display inverted pin state of $input\n' >&2 printf ' lights-out help: display this help and exit\n' >&2 printf ' lights-out init: init gpio\n' >&2 printf ' lights-out name: print the name of the server\n' >&2 printf ' lights-out push $output $time: simulate push on $output for $time seconds\n' >&2 printf ' lights-out turn on: turn on machine if not yet running\n' } check_argument_count() { local count="$1" shift if [ $# -ne "${count}" ]; then >&2 printf 'wrong number of arguments: "%s" expects %s argument' "$1" "${count}" if [ "${count}" -ne 1 ]; then printf 's' fi printf ', but %s were given\n\n' "$#" display_help exit 1 fi } if [ $# -lt 1 ]; then display_help exit 1 fi if [ ! -r '#ETCDIR#/lights-out.conf' ]; then >&2 printf 'cannot read config file "#ETCDIR#/lights-out.conf"\n' exit 1 fi if ! command -v gpio >/dev/null 2>&1; then >&2 printf 'cannot find command "gpio" - is it installed?\n' exit fi unset inputs unset outputs declare -A inputs declare -A outputs . '#ETCDIR#/lights-out.conf' if [ -z "${inputs['power']}" ]; then >&2 printf 'invalid config "#ETCDIR#/lights-out.conf": no power input defined.\n' exit 1 fi if [ -z "${outputs['power']}" ]; then >&2 printf 'invalid config "#ETCDIR#/lights-out.conf": no power output defined.\n' exit 1 fi if [ -z "${server}" ]; then >&2 printf 'invalid config "#ETCDIR#/lights-out.conf": no server name defined.\n' exit 1 fi case "$1" in 'get') check_argument_count 2 "$@" if [ -z "${inputs["$2"]}" ]; then >&2 printf 'unknown input "%s"\n\n' "$2" display_help exit 1 fi value=$( gpio read "${inputs["$2"]}" ) || exit $? echo $((1-value)) ;; 'help') display_help ;; 'init') check_argument_count 1 "$@" for input in "${inputs[@]}"; do gpio mode "${input}" in || exit $? gpio mode "${input}" up || exit $? done for output in "${outputs[@]}"; do gpio write "${output}" 0 || exit $? gpio mode "${output}" out || exit $? done ;; 'name') printf '%s\n' "${server}" ;; 'push') check_argument_count 3 "$@" if [ -z "${outputs["$2"]}" ]; then >&2 printf 'unknown output "%s"\n\n' "$2" display_help exit 1 fi gpio write "${outputs["$2"]}" 1 || exit $? sleep "$3" gpio write "${outputs["$2"]}" 0 || exit $? ;; 'turn') if [ $# -ne 2 ] \ || [ "x$2" != 'xon' ]; then >&2 printf 'unknown command "%s"\n\n' "$*" display_help exit 1 fi value=$( "$0" get power ) || exit $? if [ "${value}" -eq 0 ]; then "$0" push power 0.1 || exit $? fi ;; 'turn on') check_argument_count 1 "$@" "$0" 'turn' 'on' || exit $? ;; *) >&2 printf 'unknown command "%s"\n\n' "$1" display_help exit 1 ;; esac