#!/usr/bin/env bash

# Start the fake Proton Drive server (backend/protondrive/protontest).
#
# protonfake mints a signed in session when it starts and prints it as
# key=value lines on stdout, so the script builds it, captures that
# output and passes it on. Every user of the server shares the session.

set -e

NAME=TestProtonDriveFake
IP=127.0.0.1
PORT=28642

# This script lives in fstest/testserver/init.d; it is run from each
# test package's directory, so find the repository from here.
REPO_ROOT=$(cd "$(dirname "$0")/../../.." && pwd)

start() {
    local bin="${RUN_STATE}/protonfake"
    local out="${RUN_STATE}/protonfake.out"
    # A built binary, not "go run", so the pid is the server's own.
    (cd "${REPO_ROOT}" && go build -o "${bin}" ./backend/protondrive/protontest/cmd/protonfake) >&2
    : > "${out}"
    nohup "${bin}" -addr "${IP}:${PORT}" > "${out}" 2>> "${RUN_STATE}/protonfake.log" </dev/null &
    local pid=$!
    echo "${pid}" > "${RUN_STATE}/pid"
    disown "${pid}"

    # protonfake prints six lines, type= last, once it is listening.
    local i
    for i in $(seq 1 100); do
        if grep -q '^type=' "${out}"; then
            cat "${out}"
            echo "_connect=${IP}:${PORT}"
            return 0
        fi
        if ! kill -0 "${pid}" 2>/dev/null; then
            echo "protonfake exited: $(cat "${RUN_STATE}/protonfake.log")" >&2
            return 1
        fi
        sleep 0.1
    done
    echo "protonfake printed no config within 10s" >&2
    stop
    return 1
}

stop() {
    if status; then
        local pid
        pid=$(cat "${RUN_STATE}/pid")
        kill "${pid}"
        # protonfake finishes its requests on SIGTERM; wait so the port
        # is free for the next start.
        local i
        for i in $(seq 1 100); do
            kill -0 "${pid}" 2>/dev/null || break
            sleep 0.1
        done
        rm -f "${RUN_STATE}/pid"
        echo "${NAME} stopped"
    fi
}

status() {
    if [ -e "${RUN_STATE}/pid" ]; then
        if kill -0 "$(cat "${RUN_STATE}/pid")" >/dev/null 2>&1; then
            return 0
        fi
        rm -f "${RUN_STATE}/pid"
    fi
    return 1
}

# shellcheck disable=SC1091
. "$(dirname "$0")/run.bash"
