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

if [ -n "$VNC_PASSWORD" ]; then
    if [ ${#VNC_PASSWORD} -lt 6 ]; then
        >&2 echo "Error: VNC password needs to be at least 6 characters long"
        exit 1
    fi
else
    if [ ! -e "/home/$NSYS_USER/vnc.pass" ] ; then
        >&2 echo "Error: VNC password needs to be set via VNC_PASSWORD environment variable"
        exit 1
    fi
fi

if [ "$WITH_TIGERVNC" = "yes" ]; then
    if [ -n "$VNC_PASSWORD" ]; then
        printf "$VNC_PASSWORD\n$VNC_PASSWORD\n\n" | vncpasswd "/home/$NSYS_USER/vnc.pass" &>/dev/null
    fi
    supervisorctl start tigervnc
    RUNNING_SERVICES+=(tigervnc)
else
    if [ -n "$VNC_PASSWORD" ]; then
        x11vnc -storepasswd "$VNC_PASSWORD" "/home/$NSYS_USER/vnc.pass" &>/dev/null
    fi
    supervisorctl start x11vnc
    RUNNING_SERVICES+=(x11vnc)
fi
