#!/usr/bin/perl
# -----------------------------------------------------------------------------
# milkbone-load
# Desc: This file is the heart of milkbone.  It brings up the core and calls
# the appropriate guidance script.  There's nothing too complicated happening
# here; most of it ought to be self-explanatory.
#
# "A beginning is the time for taking the most delicate care
# that the balances are correct."
# 	- Dune
#
# -----------------------------------------------------------------------------

use strict;
use warnings;

# Load the core.  This prepares @INC for guidance script detection, and
# sets default values (e.g. $Milkbone::FatalLog).

use lib 'lib';
use Milkbone qw(slurp);

# Launch the correct guidance script based on the command-line parameters.
# Note that linking this script to milkbone-x and then invoking that link
# is equivalent to running "milkbone x". If no arguments are supplied,
# "tk" is used as the default guidance script.

my $target;
if($0 =~ /milkbone-(.*)/) {
  $target = $1;
  shift @ARGV;
}
elsif(defined($ARGV[0]) and $ARGV[0] !~ /-/) {
  $target = $ARGV[0];
  shift @ARGV;
}
else {
  $target = "tk";
}

# We know the target name now - let's run it.  This eval block is the last
# defense against exceptions.  If something doesn't get caught here, then
# something must have gone terribly wrong.  Note that the guidance script
# doesn't return until the user has closed milkbone.

my $script = slurp("guid/" . $target . ".pl", 1);

eval $script;

# Really serious exceptions will get logged into the file pointed to by
# $Milkbone::FatalLog.

if($@) {
  print $@;
  open(my $log, ">" . $Milkbone::FatalLog);
  print $log "\n" . $@;
  close($log);
}