#!/usr/bin/perl

#/* LICENSE:
#  =========================================================================
#    CMPack'04 Source Code Release for OPEN-R SDK 1.1.5-r2 for ERS7
#    Copyright (C) 2004 Multirobot Lab [Project Head: Manuela Veloso]
#    School of Computer Science, Carnegie Mellon University
#    All rights reserved.
#  ========================================================================= */

use Getopt::Long;

@behaviors=("attack", "new_attack", "goalie", "chase", "camera",
            "challenge1", "localization_test", "challenge3", "kick_test",
            "test_will", "test_slenser", "test_jbruce", "test_brettb",
            "test_mhock", "test_mpa", "test_vmh", "test_dvail2","test_generic",
	    "pup_pilot", "motion_test");

$usage = "usage: beit <behavior>
options:
-h|--help                   get help
-n|--nostop                 don't stop the stick after changing behavior

Valid behaviors are:
";

sub print_usage {
  print $usage;
  my $line_used=0;
  foreach $behavior (@behaviors) {
    $line_used+=length($behavior)+4;
    if($line_used >= 80) {
      print "\n";
      $line_used = length($behavior)+4;
    }
    print "'$behavior', ";
  }
  print "\n";
}

my $help=0;
my $behave="default";
my $nostop=0;
my $pc_card=0;

my %opts=
  (
   'help|h' => \$help,
   'nostop|n' => \$nostop
  );

Getopt::Long::Configure("bundling");

GetOptions(%opts) || (&print_usage() && die);

if($help) {
  &print_usage();
  exit(0);
}

if(-e "/sbin/cardctl") {
  $pc_card = 1;
} else {
  $pc_card = 0;
}

$#ARGV >=0 || die "no behavior specified\n";
$behave = $ARGV[0];

my $good = 0;
foreach $behavior (@behaviors) {
  if($behave eq $behavior) {
    $good = 1;
  }
}

$good || die "invalid behavior mode '$behave'\n";

my $stop = !$nostop;

open(CARDCTL_OUT,"/sbin/cardctl status |");
while(<CARDCTL_OUT>) {
  /suspended/ && do {
    printf("card suspended, please reinsert\n");
    exit(8);
  };
}

printf("mounting stick\n");
$mounted=0;
open(MOUNT_OUT,"/bin/mount |");
while(<MOUNT_OUT>) {
  m&/memstick& && do {
    $mounted=1;
  };
}

if(!$mounted) {
  system("mount /memstick");
}

$behave_file="/memstick/config/behave.cfg";
$tmp_name="/tmp/.behave.tmp_file_with_funning_name";

printf("setting behavior to '$behave'\n");
open(BEHAVE_CFG,"<$behave_file");
open(BEHAVE_TMP,">$tmp_name");
while($line=<BEHAVE_CFG>) {
  chomp($line);
  $line =~ /^(.*role\s*=\s*")[^"]*(".*)$/ && do { # " keep emacs happy
    printf BEHAVE_TMP "%s%s%s\n",$1,$behave,$2;
    next;
  };
  $line =~ /(.*)/ && do {
    print BEHAVE_TMP "$1\n";
    next;
  };
}
close BEHAVE_TMP;
close BEHAVE_CFG;

system("mv $tmp_name $behave_file");

unlink $tmp_name;

if($stop) {
  printf("unmounting stick\n");
  system("/bin/umount /memstick");

  if($pc_card) {
    printf("stopping card\n");
    system("echo 'eject' >/var/pipes/stop_memstick");
  }
}
