eval 'exec /usr/local/bin/perl -S $0 ${1+"$@"}'  # -*- Mode: perl -*-
    if 0;
#==============================================================
#
#  Abs:   3rd level iocConsole script for iocs
#
#  Name:  iocScreenStart                  
#
#  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: iocScreenStart <terminal server or executable> <port> <iocname> <stayup>
#         where terminal server = terminal server name assigned to ioc
#               or executable   = soft ioc full executable name
#         where port    = port number assigned to ioc
#         where iocname = node name or micro name
#         where stayup  = automatic restart flag (0, 1)
#
#  Facility: SLAC/ESD
#
#  Side:  
#  
#  
#  Auth:  20-NOV-2003, DRogind    (DROGIND):
#  Rev:   dd-mmm-yyyy, Whoever    (USERNAME):
#
#--------------------------------------------------------------
# Mods: (Latest to oldest)
#
#
#        13-Sept-2011, Judy Rock (jrock)
#        TEMPORARY WORKAROUND: ALWAYS USE ping, NEVER select fping
#        look for "WORKAROUND" text below to see code altered       
#        27-May-2009, Judy Rock (jrock)
#            $IOC_SCREEN has changed.  Therefore, look in $IOC/<iocname> for 
#            screenrc file first, then if it's not there, find it in
#            $IOC_SCREEN.
#        24-APR-2006, Debbie Rogind (DROGIND) added
#            option of postfixing "telnet" with port # for micro-iocs
#            Added check for os (SunOS or Linux)
#        01-APR-2006, S. Allison (saa):
#            Modified for linux platform
#        28-SEP-2004, Debbie Rogind (DROGIND)
#            changed default screen owner from cddev to cdioc 
#        27-SEP-2004, D Rogind (drogind)
#            Added screen owner logic
#        11-SEP-2004, D Rogind (drogind)
#            Added accommodations for ssh terminal server
#        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
#        15-JAN-2004, Debbie Rogind (DROGIND):
#            Added logic to connect to ioc node names when no terminal server
#
#
#==============================================================
#
# Create a named screen session if one does not already exist
#
use File::Copy;
use File::Spec;       # to get current script absolute location
use File::Basename;   # to strip off absolute dir path

# get this os type (SunOS, Linux)

if ( defined $ENV{"IOC_OWNER_OS"} ) {
    $os = $ENV{"IOC_OWNER_OS"};
} else {
    $os="SunOS";
}
#TESTING!
# THIS WORKS, BUT COMMENTING IT OUT FOR NOW
#$os="SunOS";

if (!( ($os =~ /SunOS/) || ($os =~ /Linux/)) ) {
	$os = SunOS;
}

print "os: $os \n";

# 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";

my $iocconsole;
my $screenrc;
my $screenopt;
my $screenlog;
my $ioclogdir;
my $status;

# check command arguments
usage("Too few args") if $#ARGV < 3;

my $iocname = $ARGV[2];
my $stayup  = $ARGV[3];
my $command;
my $pinging;
 
# Return if an iocconsole screen session already exists
#
$session = qx!$screen -list $iocname!;
if ( $session=~ m/\.$iocname\s/) {
    print "iocScreenStart: screen found for iocname = $iocname\n";
    exit 0;
}

# strip off port number if connecting to node name directly
# this is the case for iocs that don't have terminal servers
if (($ARGV[1] =~ /telnet/) || ($ARGV[1] =~ /rlogin/)) 
{
    @ports = split /telnet/, $ARGV[1];
    if ($#ports eq 1){
	    print "telnet  -> port = $ports[1]\n";
	    $iocconsole = $ARGV[0]." ".$ports[1];
		if ($os =~ /SunOS/){
			$pinging = "ping -c 1 $ARGV[0]";
		}
		else {
                        ###########################################
                        # DONT USE FPING 
			#$pinging = "/usr/bin/fping $ARGV[0]";
                        ###########################################
			$pinging = "ping -c 1 $ARGV[0]";
		}
	    $command = "telnet";
      }
    else {
		print "Connecting to node name (not terminal srv)...\n";
		$iocconsole = $ARGV[0];
		if ($os =~ /SunOS/){
			$pinging = "ping $iocconsole";
		}
		else {
                        ###########################################
                        # DONT USE FPING 
			#$pinging = "/usr/bin/fping $iocconsole";
                        ###########################################
			$pinging = "ping -c 1 $iocconsole";
		}
		$command = $ARGV[1];
	}

# for soft ioc, set up variables to start it.
# the stayup is done by siocStart.
} elsif ($ARGV[1] =~ /sioc/) {
    $iocconsole = $ARGV[0]." st.cmd ".$iocname." ".$stayup;
    $stayup  = 0;
    $command = "$shell siocStart.pl";
} else { 
# if ssh terminal server; different syntax than telnet
	print "terminal server ...\n";
    @ports = split /ssh/, $ARGV[1]; 
    if ($#ports eq 1){
	print "ssh terminal server -> port = $ports[1]\n";
	$iocconsole = $ARGV[0]." "."-p"." ".$ports[1];
	if ($os =~ /SunOS/){
		$pinging = "ping -c 1 $ARGV[0]";
	}
	else {
                ###########################################
                # DONT USE FPING 
		# $pinging = "/usr/bin/fping $ARGV[0]";
                ###########################################
		$pinging = "ping -c 1 $ARGV[0]";
	}
	$command = "ssh -x -l $screenOwner";
    }
    else {
	print "terminal server\n";
	$iocconsole = $ARGV[0]." ".$ARGV[1];
        print "OS is $os\n";
	if ($os =~ /SunOS/){
		$pinging = "ping -c 1 $ARGV[0]";
	}
	else {
                ###########################################
                # WORKAROUND: DONT USE FPING 
		#$pinging = "/usr/bin/fping $ARGV[0]";
                ###########################################
		$pinging = "ping -c 1 $ARGV[0]";
	}
	$command = "telnet";
    }
}

if ((!$stayup) && ($pinging)) {
    print "$pinging \n";
    system ($pinging)==0
	or die "iocScreenStart is exiting: $?";
}

$screenopt="";

# find iocCommon directory
if ( defined $ENV{"IOC"} ) {
    $iocCommon = $ENV{"IOC"};
} else {
    $iocCommon = $dirname;
}

# then, first look for screenrc in $iocCommon/$iocname
# if not found there, then look in same location as screeniocs
$screenrc="$iocCommon/$iocname/screenrc";
if (-f $screenrc) {
    $screenopt= "-c $screenrc";
} else {
    $screenrc="$iocdir/screenrc";
    if (-f $screenrc) {
	$screenopt= "-c $screenrc";
    }
}

$ioclogdir="$iocinfo/$iocname";
if (!(-d $ioclogdir)) {
    $ioclogdir = "$iocinfo";
}
$screenlog="$ioclogdir/screenlog.0";
unlink($screenlog);

if ($stayup)
{
    print "cd $ioclogdir;umask 000;$screen -D -m -S $iocname -t $iocname $screenopt $command $iocconsole\n";
    $status = 0;
    # status will be 0 when user quits out of telnet.  
    # Automatically restart in this case.  Don't ping first.  If the terminal
    # server is off, wait for it.
    while ($status == 0)
    {
	$status = system("cd $ioclogdir;umask 000;$screen -D -m -S $iocname -t $iocname $screenopt $command $iocconsole");
#	print "Screen stopped - status = $status\n";
	if ($status == 0) {
	    sleep 5;
	}
    }
}
else
{
    print "cd $ioclogdir;umask 000;$screen -d -m -S $iocname -t $iocname $screenopt $command $iocconsole\n";
    system ("cd $ioclogdir;umask 000;$screen -d -m -S $iocname -t $iocname $screenopt $command $iocconsole");  
    # Wait for new screen session to change to Multiuser mode
    #
    my $wait = 0;
    my $waitTimeout = 20;
    sleep 1;
    $session = qx!$screen -list $iocname!;
    print "$screen -list $iocname: $session\n";
    while ($session !~ m/\.$iocname/) {
	$wait++;
	if (++$wait > $waitTimeout ) {
	    print "Timeout waiting for Multiuser session $iocconsole\n";
	    exit -1;
	}
	sleep 1;
	$session = qx!$screen -list $iocname!;
    }
}

sub usage {
	my ($txt) = @_;
	print "Error: $txt\n" if $txt;
	print "\n";
	print "Usage:\n";
	print "    iocScreenStart  <terminal server> <port> <iocname> <stayup>\n"; 
	print "where\n";
	print "    <terminal server>    Name of term. server for ioc (e.g. b5as)\n";
        print "      - if no terminal server, then this is node name\n";
        print "      - if soft ioc, then this is the full executable name\n";
	print "    <port>               Port number for ioc (e.g. 2001)\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 "    <iocname>            Name of ioc\n";
        print "    <stayup>             Automatic restart (0=no, 1=yes)\n";
	print "\n";
	exit 2;
}
