#!/bin/sh

set -e

umask 117

PATH=$PATH:/sbin:/usr/sbin

SUDOERS=/etc/sudoers
SUDOERSD=$SUDOERS.d
TMP=`mktemp /tmp/sudoers.XXXXXXXXXX`
SBANNER='### Automatically added by update-sudoers start ###'
FBANNER='### Automatically added by update-sudoers end ###'

usage() {
    cat <<EOF

Copyright (c) 2006 Yauheni Kaliuta

This is free software; see the GNU General Public Licence version 2
for copying conditions. There is NO warranty.

This script makes configuration for sudo
$SUDOERS -- main sudo configuration
$SUDOERSD -- directory for partitional configurations

Usage:

 update-sudoers              - make the configuration      
 update-sudoers --help       - print this help

EOF

}

badusage()
{
   echo -e "update-sudoers: $@\n\n"
   echo "You need --help"
   exit 2
}

check_sudoers()
{
    visudo -c -f $TMP > /dev/null || {
	echo "$1 changes break sudoers"
	rm -f $TMP
	exit 1
    }
}

#[ -f $TMP ] && { echo "lock file exists"; exit 1; }

while [ "$1" != "" ]; do
   case $1
       in
       --help)
           usage
           exit 0;;
       *)
           shift;;
   esac
done

for i in $SUDOERSD/*; do 
    echo "$SBANNER" >> $TMP
    grep -v -E '^[:space:]*$' $i >> $TMP
    check_sudoers $i
    echo "$FBANNER" >> $TMP
done

if [ -f $SUDOERS ]; then
    awk -v sbanner="$SBANNER" \
	-v fbanner="$FBANNER" \
	'BEGIN {state="print"}; \
	$0==sbanner {state="hide"; next}; \
	$0==fbanner {state="print"; next}; \
	/^[:space:]*$/ {next};
	state=="print" {print}' < $SUDOERS >> $TMP
    check_sudoers $SUDOERS
fi

mv -f $TMP $SUDOERS
chown root:root $SUDOERS
chmod 440 $SUDOERS

