#! /bin/sh

if getent passwd asterisk >/dev/null ;then
	# Some halfbaked Sarge versions needed their home dir fixed:
        if [ "`getent passwd asterisk|awk -F: '{print $6}'`" = \
		"/var/run/asterisk" ];then
		usermod -d /var/lib/asterisk asterisk
        fi
else
	adduser_extra_opts=""
	# Cosmetic noise reduction
	if [ -d "/var/lib/asterisk" ]; then
    		adduser_extra_opts="--no-create-home"
	fi
	adduser --system --group --home /var/lib/asterisk \
	    $adduser_extra_opts \
        	--gecos "Asterisk PBX daemon" asterisk		
fi

for group in dialout audio; do
	if groups asterisk | grep -w -q -v $group; then
        	adduser asterisk $group
	fi
done

# Make sure all (possibly) used dirs exist and is owned by asterisk

# /var/run/asterisk is not yet handled by init.d :-(
# (/var/run/asterisk is handled in sysV script /etc/init.d/asterisk)

dirs="
        /var/log/asterisk
        /var/spool/asterisk
        /var/lib/asterisk
	/var/run/asterisk
        /etc/asterisk
"

subdirs="
        /var/log/asterisk/cdr-csv
        /var/log/asterisk/cdr-custom
        /var/spool/asterisk/dictate
        /var/spool/asterisk/meetme
        /var/spool/asterisk/monitor
        /var/spool/asterisk/monitor
        /var/spool/asterisk/system
        /var/spool/asterisk/tmp
        /var/spool/asterisk/voicemail
"

for dir in $subdirs $dirs; do
        mkdir -p "$dir"
done

for dir in $dirs; do
        chown -R asterisk: "$dir"
done


###################################
# this part should be reviewed, but it's basically trial and error
# code i wrote to make freepbx work. better solutions are welcomed.

# files need to be RW by the group
# dirs need to a+rx
chmod -R 0660 /etc/asterisk/
find /etc/asterisk/ -type d | xargs chmod ug+rx

#chmod g+s /etc/asterisk/

# this is needed because othewise sqlite cannot write to the DB
#chmod -R 0660 /var/lib/asterisk/

####################################
# If asterisk in running, reload it
# otherwise start it
if [ -f "/etc/init.d/asterisk" ];then
	if [ -f /var/run/asterisk/asterisk.pid ];then
	    invoke-rc.d asterisk reload || exit $?
	else
	    invoke-rc.d asterisk restart || exit $?
	fi
fi
