#!/usr/bin/env bash

# SPDX-FileCopyrightText: 2026 Romain Maneschi <romain@gitroot.dev>
#
# SPDX-License-Identifier: EUPL-1.2

_init() {
    local SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
    source "${SCRIPT_DIR}/waitforlog.sh"
    source "${SCRIPT_DIR}/report.sh"
}

_init
unset -f _init

SERVER_PORT="4545"
SERVER_DATA_DIR="/tmp/gitrootData"

# restart
#   If launched stop gitroot. Then start it from source and wait.
function restart() {
    APP=$(lsof -i tcp:${SERVER_PORT} | awk 'NR!=1 {print $2}') 
    if [ -z "$APP" ]; then
        report "🟢 Gitroot not launched"
    else 
        kill ${APP}
        report "🟢 Gitroot killed"
    fi
    local lastKill="⌛ Will restart ($(date +%s))"
    report "${lastKill}"
    cd ${SCRIPT_DIR}/../../server
    GIT_TRACE_PACKET=false go run -race . -data="${SERVER_DATA_DIR}" &>> /tmp/mylog.txt &
    wait_for_logs "starting SSH server on" /tmp/mylog.txt "${lastKill}"
}