#!/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:  mkauthkeys [-a | -r | --add | --remove] [-u username ] <string>
#
#DJM

# Global Variables
#
$num_args = @ARGV;

# Parse Arguments
#

# see if -g or --test or --ip or --help is specified
$host_specified = "";
$hostname = "";
$user_specified = "";
$usrname = "";
$type_specified = "";
$typename = "";
foreach $operation (@ARGV){
  if ($operation eq "-g"){
     $action = "retrieve";
  } elsif ($operation eq "--test"){
     $action = "test";
  } elsif ($operation eq "--help"){
     $action = "help";
  } elsif ($operation eq "--ip"){
     $host_specified = "y";
  } elsif (($host_specified eq "y") && ($hostname eq "")){
     $hostname = $operation;
  } elsif ($operation eq "-u"){
     $user_specified = "y";
  } elsif (($user_specified eq "y") && ($username eq "")){
     $username = $operation;
  } elsif ($operation eq "-t"){
     $type_specified = "y";
  } elsif (($type_specified eq "y") && ($typename eq "")){
     $typename = $operation;
  }
}

if (($num_args eq "0") || ($action eq "help")){
    $cmd_args = "mkmigrkeys --help";
    $status=system($cmd_args);
    if ("$status" eq "0"){
        exit 0;
    } else {
        exit 1;
    }
} elsif (($host_specified eq "y") || ($action eq "retrieve") ||
    ($action eq "test")){
    $cmd_args = "mkmigrkeys";
    foreach $arg (@ARGV) {
        $cmd_args = $cmd_args . " " . $arg;
    }

    if (($action ne "retrieve") && ($action ne "test")){
        if ($type_specified ne "y"){
            $cmd_args = $cmd_args . " -t rsa";
        }
    }
 
    $status=system($cmd_args);
    if ("$status" eq "0"){
        exit 0;
    } else {
        exit 1;
    }
}

# see if -u is specified
$i=0;
foreach $operation (@ARGV){
  $i++;
  if (($operation eq "-a") || ($operation eq "--add")) {
     $action = "add";
  } elsif (($operation eq "-r") || ($operation eq "--remove")) {
     $action = "remove";
  } elsif ($operation eq "-u"){
     $usr_specified = "y";
  } else {
     if ($usr_specified eq "y"){
        $usrname = $operation;
	if($action ne ""){
          last;
	}
     }
  }
  if(($action ne "") && ($usrname ne "")){
     last;
  } 
}
if ($usr_specified eq "y")
{
     for ($j=0; $j<$i; $j++) {
        shift @ARGV;
     }
     foreach $s (@ARGV) {
          $string = $string . $s;
     }
     $dir="/home/".$usrname;
     if (-e $dir)
     {
        $cmd_args = "/opt/hsc/bin/copysshkey -o " . $action . " -u " . $usrname . " -k " . "\'$string\'";

        $status=system($cmd_args);
        $rc = $?;
        if ($rc eq "3"){
      	  &Usage;
          exit 1
        }else
	{
	  exit $rc
	}
     }else
     {
	print("User specified does not exist.\n");
        exit 1;
     }
     exit;
}

$output_file = $ENV{HOME}."/.ssh/authorized_keys2";
if (! -w $output_file) {
   print("\n Error: $output_file does not exist or cannot be accessed. \n\n");
   exit;
}

if ($num_args < 2){
   &Usage;
   exit;
}
$action = $ARGV[0];
shift @ARGV;
foreach $s (@ARGV) {
   $string = $string . $s;
   #print("\n string=$string");
}
#print("\n action=$action=  string=$string=\n");

# Append, remove or bail out.
#
if (($action eq "-a") || ($action eq "--add")) {
   &Append_String($string);
} elsif (($action eq "-r") || ($action eq "--remove")) {
   &Remove_String($string);
} else {
   &Usage;
}


sub Usage {
   $cmd_args = "mkmigrkeys --help";
   system($cmd_args);

#   print("\n\n  mkauthkeys [-a | -r | --add | --remove] [-u username] <string>");
#   print("\n\n  Where \"-a\" and \"--add\" adds ssh key");
#   print(  "\n        \"-r\" and \"--remove\" removes key for the specified user id and host.");
#   print(  "\n        \"-u\" specifies the user name to add or remove the key.");
#   print(  "\n        You must have hmcsuperadmin authority to add or remove key for other users.");
#   print(  "\n        \"string\" is the ssh key to add to, or the id@host to remove.\n\n");
#   print(  "   Example:\n");
#   print(  "     mkauthkeys -a 'adB8fqeZs2d-gg+q joe\@somehost'\n");
#   print(  "        add ssh key generated for user joe at somehost\n");
#   print(  "     mkauthkeys -r 'adB8fqeZs2d-gg+q joe\@somehost'\n");
#   print(  "        remove the ssh key generated for user joe at somehost\n");
#   print(  "     mkauthkeys -r 'joe\@somehost'\n");
#   print(  "        remove all ssh keys generated for user joe at somehost\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;
}
