#!/usr/bin/perl

# The LearningOnline Network with CAPA
#
# verifymodown.pl - script to enforce file mode and ownership
#
# YEAR=2001
# 11/17,12/6 Scott Harrison
#
# $Id: verifymodown.pl,v 1.1 2002/05/23 19:12:25 harris41 Exp $
###

my $filename=shift @ARGV;
my $arguments=shift @ARGV;

#print "Filename: $filename\n";
#print "Arguments: $arguments\n";

my ($user)=($arguments=~/\-o (\S+)/);
my ($group)=($arguments=~/\-g (\S+)/);
my ($mode)=($arguments=~/\-m (\S+)/);
my $nofix;
$nofix=1 if $arguments=~/\-N/;

my $currentmode=(stat($filename))[2];
my $currentuser=getpwuid((stat($filename))[4]);
my $currentgroup=getgrgid((stat($filename))[5]);

my $cflag='';

unless (-l $filename) {
    $currentmode=sprintf("%.4o",($currentmode&07777));
    $cflag.="[MODE IS $currentmode SHOULD BE $mode]" if $mode ne $currentmode;
}

$cflag.="[USER IS $currentuser SHOULD BE $user]" if $user ne $currentuser;
$cflag.="[GROUP IS $currentgroup SHOULD BE $group]" 
    if $group ne $currentgroup;

if ($nofix) {
    print $cflag; exit;
}

if ($cflag) {
    `chmod $mode $filename`;
    `chown $user:$group $filename`;
}

print <<END if $cflag;
**** WARNING (how did this happen?!) ****
Fixing $filename ownership/permissions mismatch. $cflag\n";
END
