#!/usr/bin/env bash

set -euo pipefail

check_bin() {
    if [[ ! -f $BIN/$1 ]]; then
        echo "$1 not found in $BIN" >&2
        exit 1
    fi
}

find_project_root() {
    dir="$PWD"
    while [[ ! -d .phan ]]; do
        cd ..
        if [[ $PWD = / ]]; then
            echo "No .phan configuration directory found" >&2
            exit 1
        fi
    done
    pwd
    cd "$dir"
}

start_phan() {
    echo "Starting Phan daemon" >&2
    rm -f "$SOCKET"
    (cd "$PROJECT_ROOT" && exec $BIN/phan --daemonize-socket "$SOCKET") &>/dev/null &
    pid=$!
    while [[ ! -S $SOCKET ]]; do
        sleep 0.01
        if ! kill -0 $pid 2>/dev/null; then
            echo "Phan daemon failed to start" >&2
            return 1
        fi
    done
}

BIN=$HOME/.config/composer/vendor/bin
PROJECT_ROOT="$(find_project_root)"
SOCKET="$PROJECT_ROOT/.phan/phan.sock"

check_bin phan
check_bin phan_client

if [[ ! -S $SOCKET ]]; then
    start_phan
fi

tmp="$(mktemp)"
cleanup() { rm -f "$tmp"; }
trap cleanup EXIT

not_running="^Phan daemon not running"

$BIN/phan_client --daemonize-socket "$SOCKET" "$@" 2> >(tee "$tmp" | grep -v "$not_running" >&2)

if grep -q "$not_running" "$tmp"; then
    start_phan
    $BIN/phan_client --daemonize-socket "$SOCKET" "$@"
fi
