#! /usr/local/bin/perl

#
# Read a line from the given file descr, assumed to be opened to an /etc/backups
# file, and parse it.
#
#    $filesystem	name of the file system
#    $type		type of archive program to run
#    $online		directory in which to place on-line copies
#    @tags		list of tags associated with this entry
#    @chains		list of chain specs associated with this entry

sub read_backups_entry {
    local($input, *filesystem, *type, *online, *tags, *chains) = @_;
    local($line, @fields, $option);

    $online  = "";
    @tags = ();
    %chains = ();

  try_again: {
      return(0) if ! ($line = <$input>);	# EOF, return false
      chop($line);		# remove newline
      ($line) = split(/\#/, $line);	# remove comments
      @fields = split(/[ \t]+/, $line);

      redo try_again if $#fields == -1;	# nothing in this line, try next one

      if ($#fields < 1) {
	  print stderr "$hostname:$backup_file line $.: syntax is 'filesystem type [tags=tag1,tag2...] [chain=N[,M]] [online=directory]\n";
	  print stderr "skipping this entry.\n";
	  redo try_again;
      }

      $filesystem = shift(@fields);
      $type = shift(@fields);

    option_loop:
      while ($option = shift(@fields)) {
	  if ($option =~ /^tag=(.+)$/) {
	      push(@tags, $1);
	      next option_loop;
	  }

	  if ($option =~ /^chain=(.+)$/) {
	      ($chain,$level) = split(/,/, $1);

	      if ($level eq "") {
		  $chains{$chain+0} = $max_level[$chain+0];
	      } else {
		  $chains{$chain+0} = $level + 0;
	      }

	      next option_loop;
	  }

	  if ($option =~ /^online=(.+)$/) {
	      $online = $1;
	      next option_loop;
	  }

	  print stderr "$hostname:$backup_file line $.: unknown option $option, skipping this entry.\n";
	  redo try_again;
      }

    }

    return(1);
}

open(BACKUP, "backup") || die "cannot open backup\n";

$backup_file = "/tmp/foo";
$hostname = "beer";

while (&read_backups_entry("BACKUP", *filesystem, *type, *online, *tags, *chains)) {
    print "$filesystem\t$type\n";
    if ($online ne "") {
	print "    online: $online\n";
    }

    if ($#tags >= 0) {
	printf "    tags: %s\n", join(' ', @tags);
    }

    while (($key, $value) = each %chains) {
	print "    chain $key level $value\n";
    }
}

close(BACKUP);
