#!/usr/bin/perl

# getConsoleUsername:
# This script echos the name of the currently active user
# (this is useful when using Fast User Switching)
#
# This script also serves as an illustration of using the 'scutil' command.
# Note that if all you want is the name of the currently active user,
# it would suffice to do:  stat -f "%Su" /dev/console
# but this script illustrates techniques for getting other useful info.
# For example, the results from the 'scutil' command used below include
# info on all current users.:w

# Cameron Hayne (macdev@hayne.net)  July 2008
#     revised to avoid errors when no console user: December 2008

use strict;
use warnings;

my $scutil = "/usr/sbin/scutil";
my $consoleUserKey = "State:/Users/ConsoleUser";
my $results = `echo "show $consoleUserKey" | $scutil`;
#print $results;
if ($results =~ m/^\s*UID\s*:\s*(\d+)\s*$/m)
{
    my $uid = $1;
    #print "$uid\n";
}
if ($results =~ m/^\s*Name\s*:\s*(\S+)\s*$/m)
{
    my $username = $1;
    print "$username\n";
}
