#!/usr/bin/perl

my $what = uc($ARGV[0]);

if ($what eq "PUT" && $ARGV[3] =~ /^\d+$/ && available($ARGV[1],$ARGV[2])) {
   print "\nCommand being executed: ".
         "dd if=$ARGV[1] of=$ARGV[2]".
         " bs=512 count=1 seek=$ARGV[3]\n";
   system("dd if=$ARGV[1] of=$ARGV[2]".
          " bs=512 count=1 seek=$ARGV[3]");
   print "\n";
} elsif ($what eq "GET" && $ARGV[3] =~ /^\d+$/ && available($ARGV[1],"")) {
   print "\nCommand being executed: ".
         "dd if=$ARGV[1] of=$ARGV[2]".
         " bs=512 count=1 skip=$ARGV[3]\n";
   system("dd if=$ARGV[1] of=$ARGV[2]".
          " bs=512 count=1 skip=$ARGV[3]");
   print "\n";
} else {
   print "Usage: dmp [GET|PUT] [file|device] [file|device] [sector number]\n".
         "Copy file to disk sector or disk sector to file.\n\n".
         "  PUT - write file to sector of disk\n".
         "  GET - write sector of disk to file\n\n".
         "If using PUT then arguments are [file] [device] [sector number],\n".
         "where sector number is where to write to disk.\n".
         "If using GET then arguments are [device] [file] [sector number],\n".
         "where sector number is where to read from disk.\n\n";
   if (defined($ARGV[1]) && defined($ARGV[2]) && available($ARGV[1],$ARGV[2])) {
      print "One or both of the file & device can not be accessed.\n".
            "Either the file/device does not exist or you are not\n".
            "granted permission to access file/device.\n\n";
   }
}

# End of main body of code

sub available {
   my ($FH,$result) = ("",0);

   if (open($FH,'<'.$_[0])) {
      $result++;
      close($FH);
   }
   if ($_[1] ne "" && open($FH,'+<'.$_[1])) {
      $result++;
      close($FH);
   } elsif($_[1] eq "") {
      $result++;
   }

   return $result == 2?1:0;
}
