#!/bin/sh
# Turns on and off the optional services of the Total.js Developer Distros
set -eu

CATALOG=/usr/share/totaljs-developer/catalog
GROUP=totaljs-developer

usage() {
    echo "usage: totaljs-service list | enable NAME | disable NAME | status [NAME]" >&2
    exit 2
}

known() {
    [ -f "${CATALOG}/$1/docker-compose.yml" ]
}

need_root() {
    if [ "$(id -u)" != 0 ]; then
        exec sudo "$0" "$@"
    fi
}

state() {
    if systemctl is-active --quiet "totaljs-service@$1.service" 2>/dev/null; then echo running
    elif systemctl is-enabled --quiet "totaljs-service@$1.service" 2>/dev/null; then echo enabled
    else echo off; fi
}

cmd="${1:-}"
[ -n "${cmd}" ] || usage
shift

case "${cmd}" in
    list)
        while IFS="$(printf '\t')" read -r name text; do
            printf '%-9s %-8s %s\n' "${name}" "$(state "${name}")" "${text}"
        done < "${CATALOG}/index.tsv"
        ;;
    status)
        if [ $# -eq 0 ]; then exec "$0" list; fi
        known "$1" || { echo "unknown service: $1" >&2; exit 1; }
        state "$1"
        ;;
    enable)
        [ $# -eq 1 ] || usage
        known "$1" || { echo "unknown service: $1 (see: totaljs-service list)" >&2; exit 1; }
        need_root enable "$1"
        dir="/www/services/$1"
        mkdir -p "${dir}"
        # the Compose file is copied only if it is not there, so what the person edited stays
        if [ ! -e "${dir}/docker-compose.yml" ]; then
            cp "${CATALOG}/$1/docker-compose.yml" "${dir}/docker-compose.yml"
        fi
        chgrp -R "${GROUP}" "${dir}" 2>/dev/null || true
        chmod 2775 "${dir}" 2>/dev/null || true
        chmod 0664 "${dir}/docker-compose.yml" 2>/dev/null || true
        systemctl daemon-reload
        systemctl enable --now --no-block "totaljs-service@$1.service"
        echo "$1: turned on (the first time it downloads the image, it can take a minute)"
        ;;
    disable)
        [ $# -eq 1 ] || usage
        known "$1" || { echo "unknown service: $1" >&2; exit 1; }
        need_root disable "$1"
        systemctl disable --now "totaljs-service@$1.service"
        echo "$1: turned off (its data is kept in a Docker volume)"
        ;;
    *) usage ;;
esac
