#!/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): Shlomo Matichin 
##

# This script modifies the atd daemon init script, to lock it when it goes up

# default arguments currently compatible with RedHat and SuSE distributions.

use Getopt::Long;
use FindBin;
use lib "$FindBin::Bin";
use common;

GetOptions(	"initd=s" ,		\$initd ,
		"help" ,		\$usage ,
		"uninstall" ,		\$uninstall );

verify_initd_rcd();
$initd =~ s/\/$// ;
$base_init = $initd;
$atd_name = 'atd';

`whoami` =~ /root\n/ or dead "Only root may run this script!\n";
usage() if defined $usage ;
-e $base_init or
-e "$base_init/../killall" and $base_init .= '/..' or
	dead "Unable to find the init directory ($base_init)";
-w "$base_init" or
	dead "You do not have write permissions on $base_init";
-e "$base_init/atd" or
-e "$base_init/at" and $atd_name = 'at' or
	dead "Unable to find the 'atd' init script";
uninstall() and exit 1 if defined $uninstall ;
-e "$inst/atd_awk" or
	dead "MOSIX Distribution is not intact: Unable to find `$inst/atd_awk'";
install();
exit 1;
    
sub install
{
	-e "$base_init/$atd_name.pre_mosix" and
		dead "Please uninstall MOSIX before reinstalling";
	system( "mv -f $base_init/$atd_name $base_init/$atd_name.pre_mosix" ) and
		dead "Unable to backup old atd init script";
	system( "$FindBin::Bin/atd_awk < $base_init/$atd_name.pre_mosix > $base_init/$atd_name" ) and
		dead "Unable to patch atd init script";
	chmod( 0755 , "$base_init/$atd_name" ) or
		dead "Unable to chmod 755 '$base_init/$atd_name'";
	chmod( 0644 , "$base_init/$atd_name.pre_mosix" ) or
		dead "Unable to chmod 644 '$base_init/$atd_name'";
	exit ;
}

sub usage {
	print "Usage : atd [OPTION]\n";
	print "--initd=            the base init directory (default: /etc/rc.d/init.d)\n";
	print "--uninstall         uninstall\n";
	print "--help              this message\n";		
	exit ;
}

sub uninstall {
	`grep /proc/\\\$\\\$/lock $base_init/$atd_name 2>&1` =~ /\/proc\/\$\$\/lock/ or
		print "\nYour at-daemon script ($base_init/$atd_name) was not previously\n" and
		print "patched for MOSIX!\n" and
		exit ;
	-e "$base_init/$atd_name.pre_mosix" or
		dead "Unable to find the pre-MOSIX backup for the 'atd' init script";
	system( "mv -f $base_init/$atd_name.pre_mosix $base_init/$atd_name" ) and
		dead "Unable to restore the pre-MOSIX back-copy for the 'atd' init script";
	chmod( 0755 , "$base_init/$atd_name" ) or
		dead "Unable to chmod 755 '$base_init/$atd_name'";
	exit;
}
