#!/usr/bin/perl -w
##
## Copyright (c) 2001, 2002, Amnon BARAK (amnon@MOSIX.org).
## All rights reserved.
## This software is subject to the MOSIX SOFTWARE LICENSE AGREEMENT.
##
## THIS SOFTWARE IS PROVIDED IN ITS "AS IS" CONDITION, WITH NO WARRANTY
## WHATSOEVER. NO LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING
## FROM THE USE OF THIS SOFTWARE WILL BE ACCEPTED.
##
##
## Author(s): A.Spanier
##
 
# This script modifies the ssh daemon services configuration files to unlock
# remote shells in order to enable migration.
 
use FindBin;
use Getopt::Long;
use lib "$FindBin::Bin";
use common;
 
$file = "sshd";
 
GetOptions(     "initd=s" ,		\$initd ,
		"help" ,                \$usage ,
                "uninstall" ,           \$uninstall );

verify_initd_rcd();
$initd =~ s/\/$// ;
$file = "$initd/sshd";

if ( $usage ) { 
       usage();
}

if ( !(-e "$file") ) { 
	exit 0;
}


if ( !(-w "$file") ) { 
        dead "You do not have write permissions on '$file'";
}

if ( $uninstall ) {
          uninstall() ; 
          exit(0)     ;
}

if (-e "$file.pre_mosix") { 
	dead "Please Uninstall MOSIX before reinstalling";
}

install() ;
exit(0)   ;


sub install {
 
	chmod( 0644 , "$file" ) or
		dead "Unable to chmod 0644 '$file'";
	system( "mv -f $file $file.pre_mosix" ) and
                 dead "Failed to backup '$file'";
    
	open( ORIG_SSHD , "$file.pre_mosix" ) or
                dead "Unable to open '$file.pre-mosix' for reading";

	open( NEW_SSHD , ">$file" ) or
                dead "Unable to open '$file' for writing";
	
	while (<ORIG_SSHD>) {
	        if ( !($_ =~ /Starting/) ) {
			print NEW_SSHD $_;
                } else {
		        print NEW_SSHD $_;
			print NEW_SSHD "\techo 0 > /proc/\$\$/lock \n";
                }
        }

	close ( ORIG_SSHD );
	close ( NEW_SSHD  );

	chmod 0755 , $file or
		dead "Unable to chmod '$file' to rwxr-xr-x";
}

sub uninstall {
	safe_pipe_stderr_too("grep 'echo\ 0\ \>\ \/proc\/\$\$\/lock' $file 2>&1") =~ /echo/ or
		dead "Your sshd init file was not previously patched to work with MOSIX";
	-e "$file.pre_mosix" or
		dead "'$file.pre_mosix' was not found!";
	system( "mv -f $file.pre_mosix $file" ) and
                dead "Failed to restore the pre-MOSIX back-copy of $file";
	chmod( 0755 , "$file" ) or
		dead "Unable to chmod 755 '$file'";
	exit ;
}

 
sub usage {
        print "Usage : sshd [OPTION]\n";
        print "--uninstall         uninstall\n";
        print "--help              this message\n";
        exit ;
}
