#!/usr/local/munki/munki-python
# encoding: utf-8
#
# Copyright 2010-2024 Greg Neagle.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
launchapp

Created by Greg Neagle on 2010-02-05.
Modified 2010-07-13 to pass all arguments to /usr/bin/open
Launches an app only if we're called in the current
GUI user's session.
Prevents multiple copies of the app from being launched
when Fast User Switching is in use
Intended for use by a launchd LaunchAgent.
"""
from __future__ import absolute_import, print_function

import sys
import os
import subprocess
import time

# PyLint cannot properly find names inside Cocoa libraries, so issues bogus
# No name 'Foo' in module 'Bar' warnings. Disable them.
# pylint: disable=E0611
from SystemConfiguration import SCDynamicStoreCopyConsoleUser
# pylint: enable=E0611


def getconsoleuser():
    '''Uses Apple's SystemConfiguration framework to get the current
    console user'''
    cfuser = SCDynamicStoreCopyConsoleUser(None, None, None)
    return cfuser[0]


def main():
    '''Pass arguments to /usr/bin/open only if we are the current
    console user or no user and we're at the login window'''
    consoleuser = getconsoleuser().lower()
    try:
        thisuser = os.environ['USER'].lower()
    except KeyError:
        # when run via launchd at loginwindow context, os.environ['USER']
        # is undefined, so we'll return root (the effective user)
        thisuser = "root"

    if (consoleuser == thisuser or
            (consoleuser is None and thisuser == "root")):
        cmd = ["/usr/bin/open"]
        if len(sys.argv) > 1:
            cmd.extend(sys.argv[1:])
        else:
            print("Must specify an app to launch!", file=sys.stderr)
            exit(-1)
        retcode = subprocess.call(cmd)
        # sleep 10 secs to make launchd happy
        time.sleep(10)
        exit(retcode)
    else:
        # we aren't in the current GUI session
        # sleep 10 secs to make launchd happy
        time.sleep(10)
        exit(0)


if __name__ == '__main__':
    main()
