#!/usr/bin/perl

use warnings;
use strict;
use diagnostics;

use IPC::Open2;

if ( @ARGV ) {
	foreach my $arg ( @ARGV ) {
		if ( $arg =~ m!(.*?)=(.*)! ) {
			SetVariable( $1, $2 );
		} else {
			Trigger( $arg );
		}
	}
} else {
	print qq(Usage: kmtrigger.pl var=value "My Var=My Value" "The Macro?Trigger Value"\n);
}

sub SetVariable {
	my ( $var, $value ) = @_;
	print STDERR osascript( <<EOM );
tell app "Keyboard Maestro Engine"
	setvariable @{[AppleScriptArgument($var)]} to @{[AppleScriptArgument($value)]}
end tell
EOM
}

sub Trigger {
	my ( $macro ) = @_;
	my $value = '';
	if ( $macro =~ m!(.*?)\?(.*)! ) {
		$macro = $1;
		$value = $2;
	}
	print STDERR osascript( <<EOM );
tell app "Keyboard Maestro Engine"
	do script @{[AppleScriptArgument($macro)]} with parameter @{[AppleScriptArgument($value)]}
end tell
EOM
}

sub osascript {
  my( $script ) = @_;
  
  my( $read, $write );
  my $pid = open2( $read, $write, "/usr/bin/osascript" );
  print $write $script;
  close( $write );
  local( $/ ) = undef;
  my $result = <$read>;
  close( $read );
  waitpid($pid, 0);
  chomp $result; # osascript always adds a single return
  return $result;
}

sub AppleScriptArgument {
	my ( $v ) = @_;
	$v =~ s!\\!\\\\!g;
	$v =~ s!"!\\"!g;
	return qq("$v");
}