#!/usr/bin/perl

# use IO::Handle;
use File::Copy;

$SLOTS=1000;

$numArgs = $#ARGV + 1;
($numArgs == 4)
    or die ("I want 4 command line paramets.");

$FILES_BASE=$ARGV[0];
$COMMAND=$ARGV[1];
$SLOT=$ARGV[2];
$DEVICE=$ARGV[3];
$MAX_NAME_LENGTH=128;
$VOLUME_BASE_NAME="TEST-FILE1-"; # our volume name always match changer slot


sub do_slots
{
  print("$SLOTS\n");
}

sub do_list
{
  for ($i = 1; $i <= $SLOTS; ++$i) {
    printf("$i:%s%04d\n", $VOLUME_BASE_NAME, $i);
  }
}

sub do_loaded
{
  $BUFFER="";
  $LABEL="";

  if( -e $DEVICE ) {
    # lets read VOLUME name from the file
    # it's not the best way to do this .... still it works
    open(FILE, "<$DEVICE")
	or die "Couldn't open file: $!\n";

    binmode(FILE);

    seek(FILE, 93, SEEK_SET)
	or die "Couldn't seek";

    read(FILE, $BUFFER, $MAX_NAME_LENGTH)
	or die "Couldn't read";

    foreach (split(//, $BUFFER)) {
      if(ord($_) == 0) {
        last;
      }
     $LABEL=$LABEL.chr(ord($_));
    }

    printf("%d\n",substr($LABEL,14,4));
  } elsif( -e "$DEVICE" ) {
    print( "0\n" );
  }
}

sub do_unload
{
  $DST_FILE=sprintf("%s/slots/%s%04d", $FILES_BASE, $VOLUME_BASE_NAME, $SLOT);
  $SRC_FILE="$DEVICE";

  if( -e $DST_FILE ) {
    print("DST file already exists. refused to unload");
    exit 1;
  }

  if( ! -e $SRC_FILE ) {
    print("SRC file does not exists. refused to unload");
    exit 1;
  }

  move($SRC_FILE, $DST_FILE)
	or die "Couldn't move file SRC=$SRC_FILE DST=$DST_FILE";

  unlink("$SRC_FILE-mounted");
}

sub do_load
{
  $SRC_FILE=sprintf("%s/slots/%s%04d", $FILES_BASE, $VOLUME_BASE_NAME, $SLOT);
  $DST_FILE="$DEVICE";

  if( -e $DST_FILE ) {
    print("DST file already exists. refused to load");
    exit 1;
  }

  if( -e $SRC_FILE ) {
    move($SRC_FILE, $DST_FILE)
  }
}

if( $COMMAND eq 'slots' ) {
    &do_slots;
}
elsif( $COMMAND eq 'list' ) {
    &do_list;
}
elsif( $COMMAND eq 'loaded' ) {
    &do_loaded;
}
elsif( $COMMAND eq 'unload' ) {
    &do_unload;
}
elsif( $COMMAND eq 'load' ) {
    &do_load;
}

exit 0;

