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

# This script creates the nessecary symbolic links from the kernel's /include
# directory to /usr/include directories. This is important for the compilation
# of the user level programs and other MOSIX dependant programs.

# Default arguments currently compatible with all linux distributions. 

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

$include_dir	= "/usr/include" ;
$kernel_dir	= "/usr/src/linux" ;
$link_dirs	= "mos linux asm" ;

GetOptions( 	"include_dir=s" , 	\$include_dir ,
		"kernel_dir=s" ,	\$kernel_dir ,
		"ignore_not_exists" ,	\$ignore_not_exists ,
		"help" ,		\$usage ,
		"uninstall" ,		\$uninstall );

$include_dir =~ s/\/$// ;
$kernel_dir =~ s/\/$// ;

usage() if defined $usage ;
-w $include_dir or dead "You don't have permission to write to $include_dir. Symbolic links creation failed";
uninstall() and exit 1 if defined $uninstall ;
install();
exit 1;
    
sub install
{
	foreach $dir( split / / , $link_dirs ) {
		$ignore_not_exists or -d "$kernel_dir/include/$dir" or
			dead "$kernel_dir/include/$dir was not found or is not a directory. ".
				"Supply the --kernel_dir parameter (--help for usage)\n";
		
		if ( ( -e "$include_dir/$dir" ) 
		     and ( not -e "$include_dir/$dir.pre_mosix") ) {
		    
		    system( "mv -f $include_dir/$dir $include_dir/$dir.pre_mosix" ) and 
			print "Warning: unable to remove $include_dir/$dir";
		
		}

		system( "ln -sf $kernel_dir/include/$dir $include_dir/$dir" ) and
			dead "Unable to link $kernel_dir/include/$dir to $include_dir\n";
	}
	exit ;
}

sub usage {
	print "Usage : create_symlinks [OPTION]\n";
	print "--kernel_dir=   the kernel source tree root directory (default: /usr/src/linux)\n";
	print "--include_dir=  the system main include directory. (default: /usr/include)\n";
	print "--uninstall     uninstall\n";
	print "--help          this message\n";		
	exit ;
}

sub uninstall {

    
    foreach $dir( split / /,$link_dirs ) {


	if( $dir =~ /mos/ ) {
	    system( "rm -f $include_dir/$dir" ) and
		print "Unable to delete link $include_dir/$dir\n";
	} else {

	  

	    if ( -e "$include_dir/$dir.pre_mosix" ) { 

		system("rm -f $include_dir/$dir" ) and
		       print "Unable to delete link $include_dir/$dir\n";	

		system( "mv -f $include_dir/$dir.pre_mosix $include_dir/$dir" ) and
		    print "Unable to restore old link $include_dir/$dir from ".
			"$include_dir/$dir.pre_mosix\n";
		
	    }
	}
    }
    exit ;
}
