#!/bin/bash
# Ubuntu 의 systemctl 과 같은 사용법으로 OpenRC 서비스를 다루는 래퍼
set -u
action=${1:-list-units}
shift || true

need_root() {
	if [ "$EUID" -ne 0 ]; then
		echo "관리자 권한이 필요합니다: sudo systemctl $action ..." >&2
		exit 1
	fi
}

usage() {
	cat <<'USAGE'
사용법: systemctl <명령> [서비스...]     (실제 동작은 OpenRC 의 rc-service / rc-update)

  start | stop | restart | reload <서비스>   서비스 시작/중지/재시작
  status <서비스>                             상태 보기
  enable [--now] <서비스>                     부팅 시 자동 시작 (--now: 지금도 시작)
  disable [--now] <서비스>                    자동 시작 해제
  is-active | is-enabled <서비스>
  list-units                                  전체 서비스 상태     (rc-status -a)
  list-unit-files                             자동 시작 목록       (rc-update show -v)
  --failed                                    비정상 종료된 서비스
  reboot | poweroff

서비스 이름은 Ubuntu 이름도 됩니다 (ssh → sshd, cron → crond 등).
USAGE
}

now=0
units=()
for a in "$@"; do
	case $a in
		--now) now=1 ;;
		-*) ;;
		*) units+=("$(/usr/libexec/nasos/svc-name "$a")") ;;
	esac
done

need_units() {
	if [ ${#units[@]} -eq 0 ]; then
		echo "서비스 이름을 지정하세요. 예) systemctl $action ssh" >&2
		exit 1
	fi
}

rc=0
case $action in
	start|stop|restart|reload)
		need_root; need_units
		for u in "${units[@]}"; do rc-service "$u" "$action" || rc=1; done ;;
	try-restart|condrestart)
		need_root; need_units
		for u in "${units[@]}"; do
			rc-service "$u" status >/dev/null 2>&1 && { rc-service "$u" restart || rc=1; }
		done ;;
	status)
		if [ ${#units[@]} -eq 0 ]; then exec rc-status; fi
		for u in "${units[@]}"; do rc-service "$u" status || rc=3; done ;;
	enable)
		need_root; need_units
		for u in "${units[@]}"; do
			rc-update add "$u" default || rc=1
			[ "$now" = 1 ] && { rc-service "$u" start || rc=1; }
		done ;;
	disable)
		need_root; need_units
		for u in "${units[@]}"; do
			rc-update del "$u" default || rc=1
			[ "$now" = 1 ] && { rc-service "$u" stop || rc=1; }
		done ;;
	is-active)
		need_units
		for u in "${units[@]}"; do
			if rc-service "$u" status >/dev/null 2>&1; then echo active; else echo inactive; rc=3; fi
		done ;;
	is-enabled)
		need_units
		for u in "${units[@]}"; do
			if rc-update show 2>/dev/null | awk '{print $1}' | grep -qx "$u"; then echo enabled; else echo disabled; rc=1; fi
		done ;;
	list-units)      exec rc-status -a ;;
	list-unit-files) exec rc-update show -v ;;
	--failed)        exec rc-status --crashed ;;
	daemon-reload)   ;;
	reboot)          need_root; exec reboot ;;
	poweroff|halt)   need_root; exec poweroff ;;
	-h|--help|help)  usage ;;
	*)               echo "지원하지 않는 명령: $action" >&2; usage; exit 1 ;;
esac
exit $rc
