#!/bin/bash

RUN_USER="$1"

if [[ -z "$RUN_USER" ]]; then
    echo "Usage: $0 <user_name>"
    echo "Example: $0 jaguar"
    echo "Example: $0 jdoe"
    exit 1
fi

HMDIR=$(getent passwd "$RUN_USER" | cut -d: -f6)

if [[ -z "$HMDIR" ]]; then
    echo "User not found: $RUN_USER"
    exit 1
fi

if [[ -f "$HMDIR/.jaguarhome" ]]; then
    hm=$(cat "$HMDIR/.jaguarhome")
else
    hm=""
fi

if [[ -z "$hm" ]]; then
    JAGUAR_HOME="$HMDIR"
else
    JAGUAR_HOME="$hm"
fi

while true
do
    pid=$(pgrep -u "$RUN_USER" -x jaguar.bin)

    if [[ -z "$pid" ]]; then
        cd "$JAGUAR_HOME/bin" || exit 1
        ./jaguarstart
    fi

    pid=$(pgrep -u "$RUN_USER" -x lighttpd)

    if [[ -z "$pid" ]]; then
        cd "$HMDIR/fwww" || exit 1
        source venv_fwww/bin/activate
        cd bin_dir || exit 1
        ./start_all_servers.sh
    fi

    sleep 60
done


