#!/bin/bash
port=8080
source /home/svc-zsaf/virtual_envs/airflow/bin/activate

run_airflow_webserver() {
    rm -rf /home/svc-zsaf/airflow/airflow-webserver.pid
    fuser -k $port/tcp

    DATA=($(bazel run --config=cuda -c opt //zsaf/zsaf_pipeline/airflow:airflow_setup | tr -d "[',]"))

    # Set the environment variables otherwise set by Bazel
    export LD_LIBRARY_PATH=${DATA[0]}
    export PYTHONPATH=${DATA[1]}
    export RUNFILES_MANIFEST_FILE=${DATA[2]}

    # The following enables Airflow to load its own packages first, in case driving repo uses
    # older/incompatible version. However, this also implies that some package versions will
    # not be the same as what is in the driving repo. Please try to install only the bare minimum
    # required by Airflow in its virtual environment, everything else should come from the repo.
    # PYTHONPATH=/home/svc-zsaf/virtual_envs/airflow/lib/python3.6/site-packages:$PYTHONPATH

    # Move the the directory Bazel uses for the execution of the binary (important for protos)
    current_directory=${DATA[3]}
    cd $current_directory

    airflow webserver -p $port
}

until run_airflow_webserver; do
    echo "Service crashed with exit code $?. Restarting in 5 seconds..." >&2
    sleep 5
done
