#!/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;

$usage = "usage: wlan_config
options:
-d|--dogroot <root>         set root directory to use
-h|--help                   get help
-s|--static                 use a static IP address (DHCP is default)
-i|--ip <hostname>          set the dogs hostname and IP address
-o|--output <1|0>           set output to on/off
";

my $help=0;
my $ip="ers01";
my $dogroot="default";
my $nostop=0;
my $output_on=1;
my $robot_id=1;
my $static=0;

my $pc_card=0;

my %opts=
  (
   'help|h' => \$help,
   'ip|i:s' => \$ip,
   'dogroot|d:s' => \$dogroot,
   'nostop|n' => \$nostop,
   'output|o:s' => \$output_on,
   'static|s' => \$static
  );

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

GetOptions(%opts) || die $usage;

if($help) {
  print $usage;
  exit(0);
}

$output_on = $output_on + "0";
$output_on = ($output_on != 0);

if($ip    eq "default") {$ip = "ers01"}
if($dogroot eq "default") {$dogroot=$ENV{"DOGROOT"}}

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

$ip =~ /^ers(\d+)$/;
$robot_id = $1 + 0;

if(!$static){
  $ip = "DHCP";
}

print "hostname=$ip dogroot=$dogroot robot_id=$robot_id\n";

chdir "$dogroot";

if($pc_card) {
  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");
}

$DHCPconf = <<EndDhcpConf;
USE_DHCP=1
ESSID=CMU
WEPENABLE=0
WEPKEY=
APMODE=1
CHANNEL=4
EndDhcpConf

printf("copying files\n");
if($static){
  system("cp $dogroot/util/wlan_config/$ip.txt /memstick/open-r/system/conf/wlanconf.txt");
}else{
  open(WLANCONF_OUT,">/memstick/open-r/system/conf/wlanconf.txt");
  print WLANCONF_OUT $DHCPconf;
  close(WLANCONF_OUT);
}
open(WAVELAN_CFG_OUT,">/memstick/config/wavelan.cfg");
printf WAVELAN_CFG_OUT "SenderID = %d;\n",$robot_id;
printf WAVELAN_CFG_OUT "OutputOn = %d;\n",$output_on;
close(WAVELAN_CFG_OUT);

if(!$nostop) {
  printf("stopping stick\n");
  system("stopit")!=-1 || die "couldn't find stopit in your path\n";
}
