eval 'exec /usr/local/bin/perl -S $0 ${1+"$@"}'  # -*- Mode: perl -*-
    if 0;
#==============================================================
#
#  Abs:   iocConsole script  
#
#  Name:  iocConsole.pl                     
#
#  Rem:   iocConsole program provides a common mechanism for connecting 
#  to VME IOC console serial lines as well as soft IOC virtual terminal 
#  sessions. It takes advantage of gnu screen utility to provide a multiuser
#  session running telnet to manage an ioc console session.
#  - telnet session to ioc continues to run even when no users are attached
#    to the screen session
#  - ioc console output is captured and can be viewed by subsequent sessions
#  - maintains scroolback history buffer
#  - allows multiple simultaneous connections - anything typed in one
#    session appears in all of them - more than one person can be viewing
#         
#
#  Usage: iocConsole <iocname>
#         or
#         iocConsole <iocname> <terminal server or executable> <port> <host>
#         where iocname = node name, micro name, or soft ioc name.
#         Optional:
#         where terminal server = terminal server name assigned to ioc
#               or executable   = soft ioc full executable name
#         where port    = port number assigned to ioc
#         where host    = node name to run screen
#         If only iocname is provided, iocname must be included in the 
#         screeniocs files residing in either the same directory as 
#         iocConsole.pl or under $IOC_SCREEN.
#
#  Facility: SLAC/ESD
#
#  Side: 
#  
#  Auth:  20-NOV-2003, DRogind    (DROGIND):
#  Rev:   dd-mmm-yyyy, Whoever    (USERNAME):
#--------------------------------------------------------------
# Mods: (Latest to oldest)
#
#        04/11/2011 jrock
#        wipe only the selected IOC, not all dead sessions!
#        this will leave dead sessions that aren't really dead, only on the other iocCosole host
#        10-MAR-2010, J. Rock (jrock):
#        Don't call iocTSmgr with soft ioc name
#        08-MAR-2010, J. Rock (jrock):
#        Added -reset option
#        01-APR-2006, S. Allison (saa):
#        Modified for linux
#        29-SEP-2004, Debbie Rogind (DROGIND)
#        Added sub doLogging to establish logging via script
#        defined by $IOC_LOGSCRIPT
#        28-SEP-2004, Debbie Rogind (DROGIND)
#        added "-x" to ssh syntax to disable X11 forwarding
#        changed default screen owner from cddev to cdioc 
#        27-APR-2004, S. Allison (saa):
#        Changed CD_DATA to CD_DATA_IOC.
#        06-APR-2004, Debbie Rogind (drogind):
#        Added /usr/local/bin/ path to perl
#        24-FEB-2004, S. Allison (SAA):
#        Added more features.
#        10-DEC-2003, Debbie Rogind (DROGIND):
#        Modified for soft iocs for use with asd sioc* scripts
#        12-DEC-2003, Debbie Rogind (DROGIND):
#        Modified screeniocs to include prod. iocs- added host col
#        
#
#==============================================================

#
# Connect to ioc using screen
use Cwd;
use File::stat;
#use Getopt::Std;
use Getopt::Long;
use File::Spec;       # to get current script absolute location
use File::Basename;   # to strip off absolute dir path

# get absolute file path to deployed \bin dir
$me = File::Spec->rel2abs(__FILE__);

$dirname = dirname($me, ".pl");

# IOC_OWNER is unix account under which screen runs
if ( defined $ENV{"IOC_OWNER"} ) {
    $screenOwner = $ENV{"IOC_OWNER"};
} else {
    $screenOwner="cdioc";
}
# If IOC_OWNER_SHELL is set (to bash or sh), then use it for all shell
# commands with the login (-l) option.  Note that the .bashrc file is
# not sourced unless this option is set.  csh and tcsh don't have this
# restriction so IOC_OWNER_SHELL is not required.
if ( defined $ENV{"IOC_OWNER_SHELL"} ) {
    $shell = $ENV{"IOC_OWNER_SHELL"};
    if (($shell == "bash") || ($shell == "sh")) {
	$shell = "$shell -l"
    }
} else {
    $shell = "";
}
# IOC_SCREEN is location of screeniocs config file
# and optional screenrc filename (may be used w the -c option 
#  to screen, if it exists in this dir) 
if ( defined $ENV{"IOC_SCREEN"} ) {
    $iocdir = $ENV{"IOC_SCREEN"};
} else {
    $iocdir = $dirname;
}

#IOC_INFO or IOC_DATA or CD_DATA_IOC is path of bootparams file.
#It is also used in determining the location of the screenlog file if
#"deflog" is set to "on" in the screenrc file.  It is also the
#directory that will contain any core file dumped by the IOC.
if ( defined $ENV{"IOC_INFO"} ) {
    $iocinfo = $ENV{"IOC_INFO"};
} elsif ( defined $ENV{"IOC_DATA"} ) {
    $iocinfo = $ENV{"IOC_DATA"};
} elsif ( defined $ENV{"CD_DATA_IOC"} ) {
    $iocinfo = $ENV{"CD_DATA_IOC"};
} else {
    $iocinfo = ".";
}

# screen utility modified for root privilege
if ( defined $ENV{"SCREENBIN"} ) {
    $screendir = $ENV{"SCREENBIN"};
} else {
    $screendir = "/opt/screen/bin";
}
$screen ="$screendir/screen";

# sioc vars
my $command = 0;
my $siocHost = 0;
my $siocOwner = 0;
my $sioc = 0;
my $screenSession;

my ($ts,$port);
my $screenHost;
my $iocScreenCommand;
my $iocScreenCommandEnd;

my $cleanup    = 0; 
my $reset      = 0; 
my $stayup     = 0; 
my $norestart  = 0; 
my %screenIocList;
&GetOptions('cleanup' => \$cleanup, 'stayup' => \$stayup, 
	    'norestart' => \$norestart, 'reset' => \$reset);

if ($stayup) {
    $norestart = 0;
}

usage("Too few args") if $#ARGV < 0;
$iocname = $ARGV[0];
$screenSession = $iocname;

# call reset if this is a reset case, then exit:
# TESTING
if ($reset) {
   print "Initiating reset for $iocname TS port\n";
   doReset($iocname);
   exit;
}

if ($#ARGV == 3) {
    $ts         = $ARGV[1];
    $port       = $ARGV[2];
    $screenHost = $ARGV[3];
} else {
    #check for the ioc in the screeniocs list.
    $screenIocListFile= "$iocdir/screeniocs";
    if (!(-f $screenIocListFile)) {
        $screenIocListFile= "$dirname/screeniocs";
    }
    #print "my screeniocs dir $screenIocListFile\n";
    if (!(-f $screenIocListFile)) {
	print  "Error: screeniocs file = $screenIocListFile not found.\n";
	die "Error: iocConsole is terminating...ioc was has no screeniocs file\n";
    }
    getScreenIocList($screenIocListFile);
    if (!($screenIocList{$iocname})) {
	die "Error: iocConsole is terminating...ioc was not included in screeniocs file\n";
    }
}

if ($port =~ m/^sioc/) {
    $sioc = 1;
    my $bootparams="$iocinfo/bootparams";
    my $bpfile="$bootparams/$iocname";
    if (-f $bpfile) {
	getScreenInfo($bpfile);
	if ($command !~ m/^screen/ ) {
	    die "Error: iocConsole is terminating...ioc has no screen\n";
	}
	$screenOwner = $siocOwner;
	$screenHost  = $siocHost;
	$stayup      = 0;
	$norestart   = 1;
    }
    elsif (!$screenHost) {
       print  "Error: bootparam file = $bpfile not found.\n";
       die "Error: iocConsole is terminating...ioc was has no bootparam file\n";
    }
}

if ((qx(whoami) !~ $screenOwner) || (qx(hostname) !~ $screenHost)) {
    $iocScreenCommand    = "ssh -x -l $screenOwner -t $screenHost \"";
    $iocScreenCommandEnd = "\"";
}
else {
    $iocScreenCommand    = "";
    $iocScreenCommandEnd = "";
}
# see if this is a cleanup case:
if ($cleanup) {
    print "Initiating cleanup for $iocname\n";
    doIocConsoleClean();
}


if ($sioc) {
    print "processing soft ioc...\n";
} else {
    print "processing hard ioc...\n";
}
if ($norestart) {
    $iocScreenCommand= $iocScreenCommand.$screen;
    doLogging();
    print "iocConsole: $iocScreenCommand -r -S $screenOwner/$screenSession$iocScreenCommandEnd\n";
    exec("$iocScreenCommand -r -S $screenOwner/$screenSession$iocScreenCommandEnd");

} else {
    $iocScreenCommand= $iocScreenCommand." $shell ";
    if ($stayup) {
	$iocScreenCommand= $iocScreenCommand."iocScreenStart.pl";
    } else {
	$iocScreenCommand= $iocScreenCommand."iocScreen.pl";
    }
    doLogging();
    print "iocConsole: $iocScreenCommand $ts $port $iocname $stayup$iocScreenCommandEnd\n";
    exec("$iocScreenCommand $ts $port $iocname $stayup$iocScreenCommandEnd");
}

# Start a script, indicated by IOC_LOGSCRIPT to log a message 
# indicating that this user has started an iocConsole screen session. 
# If $IOC_LOGSCRIPT is undefined, return
sub doLogging {
    if ( defined $ENV{"IOC_LOGSCRIPT"} ) {
	$script = $ENV{"IOC_LOGSCRIPT"};
	$sender = qx(whoami);
	# whoami is terminated with ^J; strip off
        @lines = split /\cJ/, $sender;
        $sender = $lines[0];
	$exec_str = "$shell $script $iocname $sender";
	system($exec_str);
        print "Logged new iocConsole session for $iocname by $sender\n";
    }
}
    
# reset ts port associated with this ioc
sub doReset($) {
   my $iocnm = shift;

   print "Reset is no longer supported from iocConsole\n";
   print "Please use iocTSmgr to reset a terminal server port.\n";
   return;

   if ($iocname =~ /sioc/)
      { print "cannot -reset a soft IOC\n"; }
   else
      {
      my $exec_str = "iocTSmgr " . $iocnm . " reset";

      print "reset command is $exec_str\n";
      system($exec_str);
      }
}

# Cleanup iocConsole sessions for this ioc
sub doIocConsoleClean {
    my $wipe = 0;

    print "For $iocname, user = $screenOwner ; host = $screenHost\n";

    # screen -list
    #print  "doIocConsoleClean: $iocScreenCommand $screen -list $iocname$iocScreenCommandEnd\n";
    $status = qx($iocScreenCommand $screen -list $iocname$iocScreenCommandEnd); 
    # parse return of status   
    #print "iocname = $iocname\n";
    # split into lines
    @lines = split /^/m, $status;
    my $wipeThis = "";
    foreach $line (@lines) 
    {       
      if ($line =~ /$iocname/i) 
      {
	  $line =~ s/^\s+//;             # Remove leading whitespace

	  ($name,$value) = split (/.$iocname/,$line);
	  $name =~ s/^\s+//;             # Remove leading whitespace

          # jrock 04/11/2011 capture proc.ioc for wipe command later
          $wipeThis = $name . "." . $iocname;
# JROCK EMERGENCY FIX 5/6/2011
#	  print "There is a screen on: $line " ;
#          print "Are you sure you want to kill this (y/n)? ";
#          $input = readline(STDIN);
          $input = "y";
	  if ($input =~ /y/i)
          {
	     #print  "doIocConsoleClean: $iocScreenCommand kill -KILL $name$iocScreenCommandEnd\n";
             system ("$iocScreenCommand kill -KILL $name$iocScreenCommandEnd");
             $wipe = 1;
          }
          else { 
	     # die "Cleaning of $iocname aborted.\n";
             # exit 0;
	  }
      }

    }
    # screen -wipe
    if ($wipe)
    {
        # jrock 04/11/2011 wipe only the select IOC, not all dead sessions!
	print  "doIocConsoleClean: $iocScreenCommand $screen -wipe $wipeThis$iocScreenCommandEnd\n";
	system ("$iocScreenCommand $screen -wipe $wipeThis$iocScreenCommandEnd");
	die "Cleaning of $iocname complete.\n";
    }
    else 
    {
	die "$iocname was not cleaned.\n";
    }
    
}

# Get sioc screen info from bootparams file.
sub getScreenInfo {
  my ($fn) = @_;
  print "Open bootparams file $fn\n";
  local *IN;
  my $line;
  if (!open(IN, "$fn") ) 
  {
    print "   Can't open $fn: $!\n";
    die "Error: iocConsole is terminating... $iocname must not be started!\n";
  } 
  else 
  {
    $line = <IN>;
    chomp($line);
    #return if !($line =~ m/^hn=/);
    (@chunks) = split (/ |,|\(|\)/,$line);
    foreach $item (@chunks) {
      ($name,$value) = split (/=/,$item);
      print "name: $name, value: $value\n";
      next if $name ne "cc";  # cc = Console connection
      ($command, $siocHost, $siocOwner, $screenSession) = split (/:/,$value);
      last;
      print "command = $command; siocHost = $siocHost; siocOwner = $siocOwner; screenSession = $screenSession\n";
      # take care of case where sioc is not started ..

    }
  }
}
  
# Get a list of hard iocs to use with screen command from file.
# This list is used to see if the ioc argument is valid.
# screenHost is resolved 
sub getScreenIocList {

  my $fn = shift;
  local *IN;
  if (!open(IN, "$fn") ) {
    print "   Can't open screen usage ioc list file $fn: $!\n";
    return;
  }
  my $line;
  my @items;
  my $item;
  foreach $line ( <IN> ) {
     chomp($line);
     $line =~ s/^\s+//;             # Remove leading whitespace
     $line =~ s/\s+$//;             # Remove trailing whitespace
     $line =~ s/\s*#.*$//;          # Remove trailing comments
     next if ($line =~ /^\s*$/);    # Skip blank lines
     if ($line =~ /^$iocname\s/i) {    # store line matching ioc name
       ($nn,$ts,$port,$screenHost)= split ' ', $line, 4;
       #print "nn=$iocname, ts=$ts, port=$port, screenHost=$screenHost\n"; 
       if ($port =~ /9999/) {
	   $port = "telnet";
       }
     }
     @items = split(" ",$line);
     foreach $item (@items) {       # Allow multiple items on a line
       next if $screenIocList{$item};# Skip duplicates
       $screenIocList{$item} = 1;
       #print "ioc=$item==========from line=$line\n"; 
     }
  }
  #print "term. server / port: $match\n";
  close FILE;
}

sub usage {
	my ($txt) = @_;
	print "Error: $txt\n" if $txt;
	print "\n";
	print "Usage:\n";
	print "    iocConsole  (-<option>) <iocname> \n";
	print "where\n";
	print "    <iocname>    Hard ioc node name or micro name or soft ioc name\n";
        print "                 where a hard ioc is included in the screeniocs file\n";
        print "                 and a soft ioc has been started via 'siocStart <siocname>' \n";
	print "\n";
	print "or:\n";
	print "    iocConsole  (-<option>) <iocname> <terminal server> <port> <host>\n";
	print "where\n";
	print "    <iocname>    Hard ioc node name or micro name or soft ioc name\n";
	print "    <terminal server>    Terminal server node name\n";
        print "      - if no terminal server, then this is the ioc node name\n";
        print "      - if soft ioc, then this is the executable name\n";
	print "    <port>               Port number on the terminal server\n";
        print "      - if no terminal server, then this is 'telnet' or 'rlogin'\n";
	    print "           (telnet can be postfixed with port number)\n";
        print "      - if soft ioc, then this is 'sioc'\n";
        print "      - if ssh terminal server, then port number is prefixed with 'ssh' (e.g. ssh3033)\n";
	print "    <host>               Host where 'screen' is run\n";
	print "\n";
        print "and options:\n";
        print "    -cleanup     Kills screen session(s) named <iocname> - \n";
	print "                 prompts before killing\n";
        print "    -stayup      Start a detached screen and periodically\n";
        print "                 restart until a cleanup is done\n";
        print "    -norestart   Do not restart a detached screen\n";
        print "    -reset       performs a reset on the TS port associated with <iocname>\n";
        print "                 PLEASE NOTE: reset also does cleanup (see -cleanup above)\n";
 	print "\n";
	print "Type  ^A d  to detach from iocConsole session. \n";
	print "Type  ^A ?  for screen help. \n";
	print "\n";
	exit 2;
}
