#!/bin/sh

PATH=/usr/sbin:/usr/bin:/bin ; export PATH

radius_user="%%RADIUS_USER%%"
radius_group="%%RADIUS_GROUP%%"

radius_raddb_work="%%RADDB_WORK%%"
radius_raddb="%%RADDB%%"
radius_logdir="%%LOGDIR%%"
radius_libdir="%%LIBDIR%%"

radius_run_as_user="%%RUN_AS_USER%%"


if [ ${radius_run_as_user} != "yes" ]; then exit 0; fi

case $2 in
    PRE-INSTALL)
        # Fix the user and group in raddb/radiusd.conf
	echo "===> Setting user and group in radiusd.conf"
	for file in ${radius_raddb_work}/radiusd.conf ${radius_raddb}/radiusd.conf; do
	    if [ -w ${file} ]; then
		if ! sed -Ee "s/^[[:space:]#]*(user[[:space:]]*=[[:space:]]*).*$/\1${radius_user}/" \
		    -e "s/^[[:space:]#]*(group[[:space:]]*=[[:space:]]*).*$/\1${radius_group}/" \
		    -i .orig ${file}; then
		    echo "Failed to patch ${file}."
		    exit 1
		fi
		if [ -f ${file}.orig ]; then
                    if ! rm ${file}.orig; then
			echo "Failed to delete backup file ${file}.orig."
			exit 1
		    fi
                fi
	    fi
	done

        ;;

    POST-INSTALL)
        # Change ownership of directories
	for dir in $radius_raddb $radius_logdir/radacct \
	    /var/run/radiusd ; do
	    if [ -d $dir ] || [ -L $dir ]; then
		echo "===> Adjusting ownership of directory ${dir}"
		if ! chown -HR $radius_user:$radius_group $dir; then
		    echo "Failed to adjust ownership of ${dir}."
		    exit 1
		fi
	    fi
	done

	for file in $radius_logdir/radius.log $radius_logdir/radutmp \
	    $radius_logdir/radwtmp; do
	    if [ -f $file ]; then
		echo "===> Adjusting ownership of ${file}"
		if ! chown $radius_user:$radius_group $file; then
		    echo "Failed to adjust ownership of ${file}."
		    exit 1
		fi
	    fi
	done

	# Update the libdir line in radiusd.conf
	echo "===> Updating libdir in ${radius_raddb}/radiusd.conf"
	if ! sed -i.update-libdir-original -Ee $( \
	        echo -n 's:^(libdir[[:space:]=]+)(.*[[:space:]:]+)?' ; \
	        echo -n $( echo ${radius_libdir} | \
	            sed -Ee 's:^(.*)-[[:digit:].]+$:\1:' ) ; \
	        echo -n '(-[[:digit:].]+)?([[:space:]:]+.*)?$' ; \
		echo -n ':\1\2'${radius_libdir}'\4:' \
	    ) ${radius_raddb}/radiusd.conf; then
	    echo "Failed to update libdir in ${radius_raddb}/radius.conf"
	    exit 1
	fi

	if [ -f ${radius_raddb}/radiusd.conf.update-libdir-original ]; then
		if ! rm ${radius_raddb}/radiusd.conf.update-libdir-original; then
			echo -n 'Failed to delete backup file '
			echo "${radius_raddb}/radiusd.conf.update-libdir-original."
			exit 1
		fi
	fi

        ;;
esac


# Emacs variables

# Local Variables:
# mode: sh
# sh-basic-offset: 4
# sh-indent-comment: nil
# End:
