#!/usr/bin/bash
# Copyright Concurrent Technologies Corporation 2021
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# Initialize globals
pidAgent=0
strCallbackFile=/tmp/fapolicy-analyzer-dbus-callback.tmp
exec {fdCallback}>$strCallbackFile

# Start timestamp added to shell PID. See note in pkttyagent manpage
timestamp=$(cat /proc/$$/stat | awk '{print $22}')

# Determine if we are in a remote ssh session
if [[ ! -v SSH_TTY ]]; then
    # Note: The Gnome desktop starts its own dbus agent.
    XAUTHORITY=$XAUTHORITY
else
    # Start the dbus service agent if ssh session with a remote DISPLAY
    XAUTHORITY=$HOME/.Xauthority
    pkttyagent --notify-fd $fdCallback --process $$,$timestamp & pidAgent=$!

    # Delay if needed so that pkttyagent completes registration on the dbus.
    while ls /proc/$pidAgent/fd | grep -q $fdCallback
    do
	echo pkttyagent registering on the dbus...
        sleep 1
    done
fi

# Execute the fapolicy-analyzer with heightened privileges
pkexec  --disable-internal-agent env NO_AT_BRIDGE=1 \
	DISPLAY=$DISPLAY \
	XAUTHORITY=$XAUTHORITY \
	FAPD_LOGPATH=$FAPD_LOGPATH \
	python3 -m fapolicy_analyzer.ui "$@"

# Terminate pkttyagent if started
if [[ $pidAgent != 0 ]]; then
    echo Terminating pkttyagent.
    kill -SIGTERM $pidAgent
fi
rm -f $strCallbackFile
