#!/usr/bin/perl

# showLaunchdEnviron
# This script shows the environment (variables, etc) that is used
# for scripts run via 'launchd'.
# Cameron Hayne (macdev@hayne.net)  March 2009

use strict;
use warnings;
use File::Temp qw(tempfile);

# if you supply a command-line argument to this script,
# an environment variable named 'FOOBAR' will be defined with that value
# and put into the 'launchd' environment
my $fooBarEnvStr = '';
if (@ARGV)
{
    $fooBarEnvStr = <<EOT
    <key>EnvironmentVariables</key>
      <dict>
        <key>FOOBAR</key>
        <string>$ARGV[0]</string>
    </dict>
EOT
}

# create a script that we will run via 'launchd':
my $bashScriptText = <<'EOT';
#!/bin/bash

echo "--------------------------------------------"
echo "This script is running via 'launchd' with the following user id:"
/usr/bin/id
echo ""
echo "Environment Variables:"
/usr/bin/printenv
echo ""
echo "Current Directory:"
/bin/pwd
echo "--------------------------------------------"
EOT

#print "$bashScriptText\n";

# write the embedded Bash script to a temp file
my ($bashScriptFH, $bashScriptFile) = tempfile();
print $bashScriptFH $bashScriptText;
close($bashScriptFH);

# get another temp file to send the script output to
my ($bashScriptOutputFH, $bashScriptOutputFile) = tempfile();
close($bashScriptOutputFH);

#print "bashScriptFile: $bashScriptFile\n";
#print "bashScriptOutputFile: $bashScriptOutputFile\n";

# make the script file executable
chmod 0700, $bashScriptFile or die "Can't make script file executable: $!\n";

# create a plist for a 'launchd' job to run the above script:
my $plistLabel = 'test.foo.bar';
my $plistText = <<EOT;
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
        "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Label</key>
        <string>$plistLabel</string>
        <key>ProgramArguments</key>
        <array>
            <string>$bashScriptFile</string>
        </array>
        <key>StandardOutPath</key>
        <string>$bashScriptOutputFile</string>
        <key>StandardErrorPath</key>
        <string>$bashScriptOutputFile</string>
        <key>RunAtLoad</key>
        <true/>
        $fooBarEnvStr
</dict>
</plist>
EOT

#print "$plistText\n";

# write the embedded plist text to a temp file
my ($plistFH, $plistFile) = tempfile();
print $plistFH $plistText;
close($plistFH);

# ask 'launchctl' to load the plist (so that 'launchd' will run the script)
system("/bin/launchctl load $plistFile");

# wait a bit to allow the script time to run
sleep 1;

# ask 'launchctl' to remove the script from 'launchd'
system("/bin/launchctl remove $plistLabel");

# show the output from the script
system("/bin/cat $bashScriptOutputFile");

# remove the temp files
unlink($bashScriptFile);
unlink($bashScriptOutputFile);
unlink($plistFile);
