#!/usr/bin/eperl -w
#
# Copyright (c) Ensim Corporation 2000, 2001   All Rights Reserved.
#
# This software is furnished under a license and may be used and copied
# only  in  accordance  with  the  terms  of such  license and with the
# inclusion of the above copyright notice. This software or any other
# copies thereof may not be provided or otherwise made available to any
# other person. No title to and ownership of the software is hereby
# transferred.
#
# The information in this software is subject to change without notice
# and  should  not be  construed  as  a commitment by Ensim Corporation.
# Ensim assumes no responsibility for the use or  reliability  of its
# software on equipment which is not supplied by Ensim.
#
# Exit codes (on failure error message goes to stderr):
#  0 - success
#  1 - failure
# 
use strict;
push @INC, ($ENV{'OCW_SVCPATH'} || "/usr/lib/opcenter")."/cmdline_common";
if ($0 =~ /^(.+)\/([^\/]+)$/) {
  push @INC, $1; #the directory where the script resides
}
require CmdLineCoder;

use lib ($ENV{OCW_SVCPATH} or "/usr/lib/opcenter") . "/sendmail";
use lib ($ENV{OCW_SVCPATH} or "/usr/lib/opcenter") . "/cmdline_common";

use ERRORS;
use Carper;
use English;

#unescape the command line arguments
&CmdLineCoder::decode_args();

#
# SetForward user
#
my  $error_message = &SetForward;

if ($error_message) {
  print STDERR $error_message;
  exit 1;
}
exit 0;

sub DemoteOwnerAccessTo {
  my ($site_uid, $site_gid) = @_;
  $EFFECTIVE_GROUP_ID = $site_gid;
  $EFFECTIVE_USER_ID = $site_uid;
}

#
# Main function for setting the forward for a user
#
sub SetForward {
    my ($User);
    #Process the command line arguments
    if ($#ARGV != 0) {
    $cerr += $E_ARGS ;
	return "The number of arguments is wrong.\n";
    }

    $User = $ARGV[0];

    my ($forward)="/home/$User/.forward";
    my (@pwent)=getpwnam($User);

    &DemoteOwnerAccessTo($pwent[2], $pwent[3]);

    my (@fwd)=();
    if ( -f $forward) {
	#we keep the old vacation lines
	unless (open(FWD,$forward)) {
        $cerr += $E_UNABLEOPENFWFILE and $cerr += { fwd => $forward, user => $User } ;
	    return "Cannot open forward file $forward for $User .\n";
	}
	@fwd=<FWD>;
	close(FWD);
    
	@fwd = grep {$_ =~ /(\"\|)(\/usr\/sbin\/){0,1}(vacation )/ } @fwd; 
    }
    #Now we add the new stuff
    push @fwd,<STDIN>;
    @fwd = grep {$_ !~ /^\#noforward\#$/} @fwd;
    #Let's write it back
    if (@fwd) {
	unless (open(FWD,">$forward")) {
        $cerr += $E_UNABLEWRITEFWFILE and $cerr += { fwd => $forward, user => $User } ;
	    return "Cannot write to forward file $forward for $User .\n";
	}
	print FWD @fwd;
	close(FWD);
	if (@pwent) {
	    chown($pwent[2],$pwent[3],$forward);
	    chmod 0644,$forward;
	} else {
        $cerr += $E_NOUSERINFO and $cerr += { user => $User } ;
	    return "Could not get information on $User .\n";
	}
    } else {
	unlink($forward);
    }
    return "";
}
