#!/bin/zsh -l
# vim: fileencoding=utf-8 ft=zsh noet sw=4 ts=4 sts=4

zparseopts -D \
	h=H -help=H \
	-default+:=STATE \
	u+:=UP -up+:=UP \
	d+:=DOWN -down+:=DOWN

if [[ -n $H ]]; then cat <<END
usage: ${0:t} [options] [SVDIR]

options:
  -h --help            this help
     --default STATE   put services in a state by default:
                       "up" - turn services on
                       "down" - turn services off
                       "new-down" - turn services that weren't initialized yet off
                       "keep" - keep the current state
  -u --up PATTERN      turn on services with name matching PATTERN
  -d --down PATTERN    turn off services with name matching PATTERN
END
	exit 0
fi

[[ -r /etc/zsh/zlogin ]] && source /etc/zsh/zlogin
[[ -r /etc/zsh/zprofile ]] && source /etc/zsh/zprofile

SVDIR=${1:-${SVDIR:-/run/service}}
export SVDIR

mkdir -p ${SVDIR}

DEFAULT=${${STATE[-1]}:-new-down}
case $DEFAULT in 
	(up) zsvgen --all-up;;
	(down) zsvgen --all-down;;
	(new-down) zsvgen --new-down;;
	(keep);;
	(*)
		printf >&2 "Invalid default state: '%s'\n" $STATE
		exit 2
		;;
esac

for flag pat in "$UP[@]"; do
	zsvgen --all-up --filter $pat
done

for flag pat in "$DOWN[@]"; do
	zsvgen --all-down --filter $pat
done

# close filedescriptors and run runsvdir with some place to log
exec <& - >& - 2>& - \
  runsvdir -P ${SVDIR} \
  ${2:-................................................................................}