#!/bin/ksh
#
# permcalc.sh
#
# Shell script to work out correct chmod command required for UNIX
# file permissions eg r-sr-xr-x is 4555
#
# John Roebuck 23/12/1999

if [ $# -ne 1 ]
   then echo ""
	echo "Usage : $0 file-permission (eg r-srwxr--  must be 9 chracters)"
	echo ""
        exit 1
fi

a=0
b=0
c=0
d=0
lengthcheck=`echo $1 | wc -c`
lengthcheck=`expr $lengthcheck + 0`

if [ $lengthcheck -ne 10 ]
   then echo ""
        echo "Error : $0  file permission input must be 9 characters"
        echo ""
	exit 2
fi

for i in 1 2 3 4 5 6 7 8 9
do
	fileperm[$i]=`echo $1 | cut -c$i`
done

#
# User permissions
#

if [ ${fileperm[1]} = "r" ]
then
	a=`expr $a + 4`
fi

if [ ${fileperm[2]} = "w" ]
then
	a=`expr $a + 2`
fi

if [ ${fileperm[3]} = "x" ]
then
	a=`expr $a + 1`
fi

if [ ${fileperm[3]} = "S" ]
then
	d=`expr $d + 4`
fi

if [ ${fileperm[3]} = "s" ]
then
	a=`expr $a + 1`
	d=`expr $d + 4`
fi

#
# Group permissions
#

if [ ${fileperm[4]} = "r" ]
then
	b=`expr $b + 4`
fi

if [ ${fileperm[5]} = "w" ]
then
	b=`expr $b + 2`
fi

if [ ${fileperm[6]} = "x" ]
then
	b=`expr $b + 1`
fi

if [ ${fileperm[6]} = "S" ]
then
	d=`expr $d + 2`
fi

if [ ${fileperm[6]} = "s" ]
then
	b=`expr $b + 1`
	d=`expr $d + 2`
fi

#
# Other permissions
#

if [ ${fileperm[7]} = "r" ]
then
	c=`expr $c + 4`
fi

if [ ${fileperm[8]} = "w" ]
then
	c=`expr $c + 2`
fi

if [ ${fileperm[9]} = "x" ]
then
	c=`expr $c + 1`
fi

if [ ${fileperm[9]} = "t" ]
then
	d=`expr $d + 1`
fi


#
# Display answer
#

if [ $d = 0 ]
then
	echo "\nchmod "$a$b$c" filename\n"
else
	echo "\nchmod "$d$a$b$c" filename\n"
fi

