
#
# This script will remove the "comms-backup" entry
# from a user's crontab file. 
#

#
# Process command line arguments
#

while ($_ = shift) {
  if (/^-server$/) {
    $server = shift;
  } elsif (/^-token$/) {
    $id = shift;
    $id = "\U$id";
  } elsif (/^-backup$/) {
    $backup = shift;
  } elsif (/^-usage(.*)/) {
    print "usage: disable-backup -token <software id> -server <hostname:port> -host <hostname> -backup <file>\n";
    exit;
  } else {
    print "unknown option: $_\n";
  }
} 

unless ($id =~ /.+/) {
  print "usage: disable-backup -token <software id> -server <hostname:port> -backup <file>\n";
  exit 1;
} 
unless ($server =~ /(.+):(\d+)/) {
  print "usage: disable-backup -token <software id> -server <hostname:port> -backup <file>\n";
  exit 1;
} 
unless ($backup =~ /.+/) {
  print "usage: disable-backup -token <software id> -server <hostname:port> -backup <file>\n";
  exit 1;
} 

#
# Here we use the backup file as both a temporary file
# to install the new crontab (because cron expects a
# filename as an argument), and a file to save the old
# crontab
#

$string = `crontab -l`;
$original = $string;
if ($string =~ s/###BEGIN NEOS CHECKER ENTRY \(token = $id server = $server\)###\n(.*\n)*###END NEOS CHECKER ENTRY \(token = $id server = $server\)###\n//i) {

  if ($string eq "") {
    system("crontab -r 2>&1");
  } else { 

    # new crontab

    open (handle,">$backup");
    print handle $string;
    close handle;
    system("crontab $backup 2>&1");
  }

  # old crontab saved to backup file

  open (handle,">$backup");
  print handle $original;
  close handle;
  print "The original crontab was saved to:\n $backup\n";
  exit 0;
} else {
  print stderr "disable-backup: No crontab entry found for \"$id.\" Crontab not altered.\n";
  exit 1;
}
