#!/bin/sh
#. /etc_ro_fs/init.d/common
. /etc/autoconf.conf

if (test -f "/dl/samba.conf"); then
   . /dl/samba.conf
fi

config_dir="/etc/config"
config_file="$config_dir/smb.conf"
mount_dir="/var/usbmount"


niveau () {
        set $(echo $1 | sed -e 's/\./ /g')
        mask=$(( ($1<<24) | ($2<<16) | ($3 << 8) | $4 ))
        i=0
        while [ $i -lt 32 ]; do
                if [ $(( ($mask >> $i) & 1)) -eq 1 ]; then
                        echo $((32-$i))
                        break
                fi
                i=$(($i+1))
        done
        [ $i -eq 32 ] && echo 0
}

add_shared_directory()
{	
	count=$1
	path=$2
	
	if [ $count = 1 ]; then 
		public_name="$SAMBA_DEVICE_NAME"
	else
		public_name="$SAMBA_DEVICE_NAME$count"
	fi
	echo "[$public_name]" >> $config_file
   	echo "   comment = USB disk $public_name " >> $config_file
   	echo "   path = $mount_dir/$path" >> $config_file
   	echo "   public = yes" >> $config_file
	echo "   writable = yes" >> $config_file
	echo "   printable = no" >> $config_file
	echo "   fstype = FAT" >> $config_file
	echo "   max connections = 3" >> $config_file
}

update_config_file()
{
  	if [ ! -d $config_dir ]; then
    		mkdir $config_dir
  	fi
	
	echo "# smb conf file" > $config_file
	echo "[global]"	>> $config_file
	echo "   workgroup = $SAMBA_WORKGROUP" >> $config_file
	echo "   server string = Samba Server" >> $config_file
   	echo "   load printers = no" >> $config_file
	echo "   log file = /var/smb.log" >> $config_file
	echo "   max log size = 1" >> $config_file
	echo "   security = share" >> $config_file
	echo "   encrypt passwords = yes" >> $config_file
	echo "   socket options = TCP_NODELAY" >> $config_file
	echo "   dns proxy = no" >> $config_file
	echo "   local master = yes" >> $config_file
	echo "   preferred master = yes" >> $config_file
	echo "   wins support = yes" >> $config_file
	echo "   max xmit = 65535" >> $config_file
	echo "   dfree command = /usr/sbin/dfree" >> $config_file
	echo "   deadtime = 1" >> $config_file
	echo "   keepalive = 60" >> $config_file

	level=$(niveau $NETMASK_0)
	echo "level: $level"
	echo "   interfaces=$IP_0/$level 127.0.0.1/31" >> $config_file
	
	list_dir=$(ls $mount_dir)
	count=1
	for directory in $list_dir; do
		add_shared_directory $count $directory
		count=$(($count+1))
	done
	
	
}


case $1 in
	start)
		[ "$ENABLE_SAMBA" != 1 ] && exit;
		$0 stop
		update_config_file
		/usr/sbin/smbd -D
		/usr/sbin/nmbd -D
		;;
	stop)
		killall smbd
		killall nmbd
		;;
	update)
		update_config_file
		killall -HUP smbd
		;;
	*)
		echo "do nothing"
esac
