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

width=$NSYS_WINDOW_WIDTH
height=$NSYS_WINDOW_HEIGHT

# silence privacy settings window
function update_privacy_settings_via_manifest() {
    local manifest_filename
    manifest_filename=$NSYS_WORKSPACE/$HOST_FOLDER_NAME/Plugins/QuadDPlugin/Manifest.js
    if ! grep -Fxq "doesNotRequirePrivacySettings" "$manifest_filename"; then
        local section_match
        section_match="hostApplication:\s*\r*\n*\s*{"
        local section_insert
        section_insert="hostApplication:\n{"
        local insert_str
        insert_str="doesNotRequirePrivacySettings: true,"
        sed -i "s/$section_match/$section_insert\n$insert_str/" "$manifest_filename"
    fi
}

update_privacy_settings_via_manifest
# silence the telemetry collection window
export QUADD_ALWAYS_DISABLE_TELEMETRY=1

touch ~/.Xauthority
xauth generate "$DISPLAY" . trusted 
xauth add "${HOST}${DISPLAY}" . "$(xxd -l 16 -p /dev/urandom)"

important_pids=""
echo "Trying to start nsys-ui"
QT_AUTO_SCREEN_SCALE_FACTOR=1 QT_ENABLE_HIGHDPI_SCALING=1 "$NSYS_WORKSPACE/$HOST_FOLDER_NAME/nsys-ui" --automated &
important_pids="$important_pids $!"
sleep 1

python3.8 maximize_window.py "$width" "$height" &

echo "Waiting fo nsys-ui"
for _ in $important_pids; do
    wait -n
    break
done

echo "nsys-ui finished"

[[ -z "$(jobs -p)" ]] || kill -9 "$(jobs -p)"
