#!/bin/bash

set -e
set -u

usage() {
    echo "Usage: $0 {start|stop|status}" >&2
}

if [ $# -eq 0 ]; then
    echo "Error: No command provided." >&2
    usage
    exit 1
fi

DROP_INS_DIR="/etc/lwr/static-config/lwr-usb-gadget-configurator.d"

start() {
    for file in $(ls "${DROP_INS_DIR}"/* 2>/dev/null | sort); do
        if [[ -f "${file}" && -x "${file}" ]]; then
            echo "Starting step: $(basename ${file})"
            "${file}" start "$@"
        fi
    done
}

stop() {
    for file in $(ls "${DROP_INS_DIR}"/* 2>/dev/null | sort -r); do
        if [[ -f "${file}" && -x "${file}" ]]; then
            echo "Stopping step: $(basename ${file})"
            "${file}" stop "$@"
        fi
    done
}

status() {
    UDC_FILE="${DROP_INS_DIR}/90-udc"
    if [[ -f "${UDC_FILE}" && -x "${UDC_FILE}" ]]; then
        # Optimize run time by calling only the UDC status step, if exists
        "${UDC_FILE}" status "$@"
    else
        # Request status from all steps
        for file in $(ls "${DROP_INS_DIR}"/* 2>/dev/null | sort); do
            if [[ -f "${file}" && -x "${file}" ]]; then
                "${file}" status "$@"
            fi
        done
    fi
}

case "$1" in
    start|stop|status)
        "$@"
        ;;
    *)
        echo "Error: Unknown command '$1'." >&2
        usage
        exit 1
        ;;
esac
