#!/bin/bash

show_help() {
    echo "usage: network-state wait-listen-port <PORT>"
    echo "       network-state make-network-service <SERVICE_NAME> <PORT>"
}

wait_listen_port(){
    local port="$1"

    for _ in $(seq 120); do
        if ss -lnt | grep -Pq "LISTEN.*?:$port +.*?\\n*"; then
            break
        fi
        sleep 0.5
    done

    # Ensure we really have the listen port, this will fail with an
    # exit code if the port is not available.
    ss -lnt | grep -Pq "LISTEN.*?:$port +.*?\\n*"
}

make_network_service() {
    local service_name="$1"
    local port="$2"

    systemd-run --unit "$service_name" sh -c "while true; do printf 'HTTP/1.1 200 OK\\n\\nok\\n' |  nc -l -p $port -w 1; done"
    wait_listen_port "$port"
}

main() {
    if [ $# -eq 0 ]; then
        show_help
        exit 0
    fi

    local subcommand=$1
    local action=
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help)
                show_help
                exit 0
                ;;
            *)
                action=$(echo "$subcommand" | tr '-' '_')
                shift
                break
                ;;
        esac
    done

    if [ -z "$(declare -f "$action")" ]; then
        echo "network-state: no such command $subcommand" >&2
        show_help
        exit 1
    fi

    "$action" "$@"
}

main "$@"
