#!/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

test_display=9
new_virtual_display=
xvfb_pid=

for _ in $(seq 90); do
    # shellcheck disable=2181
    while [ $? = 0 ]; do
        new_virtual_display=:$test_display
        test_display=$((test_display + 1))
        xdpyinfo -display $new_virtual_display >/dev/null 2>&1
    done
    export DISPLAY=$new_virtual_display
    cp "$NSYS_WORKSPACE"/conf.d.later/xvfb.conf "$NSYS_WORKSPACE"/conf.d/
    sed -i -e "s/%(ENV_DISPLAY)s/$DISPLAY/g" "$NSYS_WORKSPACE"/conf.d/xvfb.conf
    sed -i -e "s/%(ENV_NSYS_WINDOW_WIDTH)s/$NSYS_WINDOW_WIDTH/g" "$NSYS_WORKSPACE"/conf.d/xvfb.conf
    sed -i -e "s/%(ENV_NSYS_WINDOW_HEIGHT)s/$NSYS_WINDOW_HEIGHT/g" "$NSYS_WORKSPACE"/conf.d/xvfb.conf

    supervisorctl reread
    supervisorctl update
    supervisorctl start xvfb  
    # wait at max 30 seconds for Xvfb to start
    for _ in $(seq 30); do
        sleep 1
        xvfb_pid=$(supervisorctl pid xvfb)
        if [ -n "$xvfb_pid" ]; then
            break
        fi
    done

    xdpyinfo -display $DISPLAY >/dev/null 2>&1
    if [ $? -ne 0 ]; then
        sleep 1
        continue
    fi
    break
done

xdpyinfo -display $DISPLAY >/dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "Xvfb is failed to started on $DISPLAY"
    export DISPLAY=
    exit 1
fi
