#!/usr/bin/perl
#
# Script to add/ remove entries to/from a file.
#
# The name of the edited file is assigned to the global variable $output_file.
#
# Syntax:  createAuthKey -d <directory> [-a | -d ] <key>
#

# Global Variables
#
$num_args = @ARGV;

# Parse Arguments
#
$dir = $ARGV[0];
$homedir = $ARGV[1];
$action = $ARGV[2];
shift @ARGV;
shift @ARGV;
shift @ARGV;
foreach $s (@ARGV) {
   $string = $string . $s;
   #print("\n string=$string");
}

$output_file = $homedir."/.ssh/authorized_keys2";

if (! -w $output_file) {
   print("\n Error: $output_file does not exist or is not accessible. \n\n");
   exit 1;
}
# Append, remove or bail out.
#
if ($action eq "-a") {
   &Append_String($string);
} elsif ($action eq "-r") {
   &Remove_String($string);
} else {
   &Usage;
}


sub Usage {
   print("\n\n  createAuthKey -d <directory> [-a | -r] <string>");
   print(  "\n  Where \"-d\" user home directory to use.");
   print("\n\n        \"-a\" adds ssh key");
   print(  "\n        \"-r\" removes key for the specified user id and host.");
   print(  "\n        \"string\" is the ssh key to add to, or the id@host to remove.\n\n");
}

sub Append_String {
   my ($str) = $_[0];

   open(OUTPUT_FILE,">>$output_file");
   print OUTPUT_FILE "$str\n";
   close(OUTPUT_FILE);

   return;
}

sub Remove_String {
   my ($str) = $_[0];
   my ($tmpfile) = "__mkauthkeystmpfile__";
   $tempstr = $str;
   $str =~ s/\+/PLUS/g;
   $str =~ s/\*/ASTERISK/g;
   $str =~ s/\$/DOLLAR/g;
   $str =~ s/\^/CARET/g;
   $str =~ s/\(/RIGHTPARENT/g;
   $str =~ s/\)/LEFTPARENT/g;
   $str =~ s/\\/BACKSLASH/g;
#   print("\n input string=$tempstr \n");

   # Copy output_file to temp file.
   #
   $rc = system("cp $output_file $tmpfile");

   # If copy was successful, remove all strings matching input pattern.
   #
   if ($rc == 0) {
      open(OUTPUT_FILE,">$output_file");
      open(TMP_FILE,"<$tmpfile");
#      print("\n string=$str");
      foreach $line (<TMP_FILE>) {
#         print("\n line=$line");
	 $linecopy=$line;
   	 $line =~ s/\+/PLUS/g;
   	 $line =~ s/\*/ASTERISK/g;
   	 $line =~ s/\$/DOLLAR/g;
   	 $line =~ s/\^/CARET/g;
   	 $line =~ s/\(/RIGHTPARENT/g;
   	 $line =~ s/\)/LEFTPARENT/g;
   	 $line =~ s/\\/BACKSLASH/g;
	 if ($line !~ m/^$str$/) {
#	   print("\n not a perfect match \n");
	   if ($str !~ m/^ssh/) {
#	     print("\n input does not starts with ssh \n");
	     if ($line !~ m/$str$/) {
   	       print OUTPUT_FILE "$linecopy";
	     }
	   }else {
   	     print OUTPUT_FILE "$linecopy";
	   }
	 }
      }
      close(TMP_FILE);
      unlink($tmpfile);
      close(OUTPUT_FILE);
   } else {
      print("\n Unable to copy $output_file to temporary location\n\n");
   }

   return;
}
