#!/usr/bin/perl

use IO::Socket::INET;

###############################################
#
# Configuration section

# Cheat mode selection
$CHEAT_MODE=0; # No cheating
#$CHEAT_MODE=1; # Use recorded sink packets

# Whether we actually send bundles or just display received
# data from the sink
$TX_BUNDLE=0;

# Sink TCP socket
$SINK_IP="10.0.2.2";
$SINK_PORT="9001";

# EID for DTN communication
$SOURCE_EID="dtn://toulouse.dtn/satnex";
$DEST_EID="dtn://genoa.dtn/satnex";

# Bundle size (ie: how
# to packetize the TCP
# stream)
$BUNDLE_SIZE=25;

# Full pathname of the dtnsend application
$DTN_SEND="./dtnsend";

###############################################
#
# Real stuff starts here

# Transmit to the sink replay packets, 
# read replies from the sink and proxy
# these replies on bundle
sub noCheat() {

  my $PACKET_HANDLE, $BUNDLE_HANDLE;
  my $sink_socket,@packet_trace;
  my $sink_msg;

    
  ## At this point, we should be ready to receive data
  ## from the sens. net sink





  # Loop for receiving the data 
  # from the sink
  while(1) {
    
    # Read data from the sink
    $sink_msg='';
    $sink_socket->recv($sink_msg,$BUNDLE_SIZE,0);
    # Active wait ... not very clever but it works
    while(length($sink_msg)==0) {
      $sink_msg='';
      $sink_socket->recv($sink_msg,$BUNDLE_SIZE,0);
    }
    
    # Shall we send bundles or simply 
    # dump hex data on the screen ? 
    if($TX_BUNDLE==0) {
      @received_data=unpack("c*",$sink_msg);
    
      print "(0..$#received_data )> ";
      for($i=0;$i<=$#received_data;$i++) {
        print sprintf("%.2X ",$received_data[$i] & 0xFF);
      }
      print "\n";
    } else {

      # Create a file using the data read from the file
      open(BUNDLE_HANDLE,">bundle.dat") || die $!;
      write(BUNDLE_HANDLE,$sink_msg,length($sink_msg));
      close(BUNDLE_HANDLE);
    
      # Send this file as a bundle through
      # the long haul link
      system("$DTN_SEND -s $SOURCE_EID -d $DEST_EID -t f -p bundle.dat");
    
      # Delete the file
      system("rm bundle.dat"); 
    }
    
  } # End of the loop  
  
  # close the socket
  close(SINK_HANDLE);
}





# Decode a HEX string and return
# an array of integers
sub decodeHexString() {

  my $a_string=$_[0];
  my @the_chars;
  my $i;
  my @buffer=();

  @the_chars=split(" ",$a_string);
  for($i=0;$i<=$#the_chars;$i++) {

    $buffer[$#buffer+1]=hex($the_chars[$i]);
  }

  return(@buffer);
}


if($CHEAT_MODE==0) {
  do noCheat();
} elsif($CHEAT_MODE==1) {
  do cheatMode1();
}
