#!/bin/bash

# SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. 
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation and any modifications thereto. Any use, reproduction, 
# disclosure or distribution of this material and related documentation 
# without an express license agreement from NVIDIA CORPORATION or 
# its affiliates is strictly prohibited.

set -e

_sigterm() {
    echo "_sigterm captured"
    pkill -P $$ || true
    exit 1
}
_sigint() {
    echo "_sigint captured"
    pkill -P $$ || true
    exit 1
}

trap _sigterm SIGTERM
trap _sigint SIGINT

function wait_service_is_ready() {
    local service_name=$1
    for _ in $(seq 60); do
        sleep 1
        service_pid=$(supervisorctl pid $service_name)
        if [ -n "$service_pid" ]; then
            break
        fi
    done
    echo $service_pid
}

function wait_container_is_ready() {
    for service in "${RUNNING_SERVICES[@]}"
    do
        service_pid=$(wait_service_is_ready "$service")
        if [ -z "$service_pid" ]; then
            >&2 echo "Error: $service is failed to start. Exiting..."
            exit 1
        fi
    done 
    printf "Docker container is ready and can be accessed via: VNC"
    if [ "$WITH_RDP" = "yes" ]; then
        printf ", RDP"
    fi
    if [ "$WITH_NOVNC" = "yes" ]; then
        printf ", HTTP"
    fi
    printf "\n"
}

echo "Waiting for services to start..."

{
    # dummy environment variable to start supervisord
    DISPLAY=:99

    # nothing that depends on Xvfb should be started here
    supervisord -c "$NSYS_WORKSPACE/supervisord.conf" &

    sleep 5
    echo "supervisord started"

    RUNNING_SERVICES=(xvfb nsys-ui jwm)
    # shellcheck source=/dev/null
    source "$NSYS_WORKSPACE"/runxvfb.sh

    # environment variables are not reread by supervisor. Replace it manually
    find "$NSYS_WORKSPACE"/conf.d.later/ -type f -not -iname 'xvfb.conf' -printf "%f\n" -exec cp '{}' "$NSYS_WORKSPACE/conf.d/" \;
    find "$NSYS_WORKSPACE/conf.d/" -type f -exec sed -i -e "s/%(ENV_DISPLAY)s/$DISPLAY/g" {} \;

    supervisorctl reread
    supervisorctl update
    source "$NSYS_WORKSPACE"/runvnc.sh

    supervisorctl start jwm
    if [ "$WITH_NOVNC" = "yes" ]; then
        supervisorctl start websockify
        RUNNING_SERVICES+=(websockify)
    fi
    if [ "$WITH_RDP" = "yes" ]; then
        sed -i -e "s/%(ENV_NSYS_VNC_PORT)s/$NSYS_VNC_PORT/g" /etc/xrdp/xrdp.ini
        sed -i -e "s@%(ENV_NSYS_WORKSPACE)s@$NSYS_WORKSPACE@g" /etc/xrdp/xrdp.ini
        supervisorctl start xrdp
        RUNNING_SERVICES+=(xrdp)
    fi

    supervisorctl start nsys-ui
} > /dev/null

wait_container_is_ready

wait
