#!/bin/sh
set -eu

usage() {
    printf '%s\n' "usage: left4me-systemctl enable|disable|show <server-name>" >&2
    exit 2
}

validate_name() {
    name=$1
    [ -n "$name" ] || usage
    case "$name" in
        .*|*..*|*/*|*\\*) usage ;;
    esac
    case "$name" in
        *[!A-Za-z0-9_.-]*) usage ;;
    esac
}

[ "$#" -eq 2 ] || usage
action=$1
name=$2

case "$action" in
    enable|disable|show) ;;
    *) usage ;;
esac

validate_name "$name"
unit="left4me-server@${name}.service"
if [ -x /bin/systemctl ]; then
    systemctl=/bin/systemctl
elif [ -x /usr/bin/systemctl ]; then
    systemctl=/usr/bin/systemctl
else
    printf '%s\n' 'systemctl not found at /bin/systemctl or /usr/bin/systemctl' >&2
    exit 69
fi

case "$action" in
    enable) exec "$systemctl" enable --now "$unit" ;;
    disable) exec "$systemctl" disable --now "$unit" ;;
    show) exec "$systemctl" show --property=ActiveState --property=SubState "$unit" ;;
esac
