#!/bin/sh

smb_config="/etc/config/smb.conf"
## echo colorful.
RED="\e[31;1m"
GRN="\e[32;1m"
YEL="\e[33;1m"
BLU="\e[36;1m"
OFF="\e[0m"

## echo with red color
## $1: output string
echor()
{
	/bin/echo -e "${RED}${@}${OFF}"
}

## echo with yellow color
## $1: output string
echoy()
{
	/bin/echo -e "${YEL}${@}${OFF}"
}

## echo with blue color
## $1: output string
echob()
{
	/bin/echo -e "${BLU}${@}${OFF}"
}

## echo with green color
## $1: output string
echog()
{
	/bin/echo -e "${GRN}${@}${OFF}"
}

## Redirect samba log and restart samba.
## $1: working directory
samba_log_redirect()
{
	log_path=${1-/share/Public}
	smb_script="/etc/init.d/smb.sh"
	[ ! -d ${log_path} ] && echor "\"${log_path}\" no such directory, stopped." && return 1

	grep -n "\-l ${log_path}" ${smb_script}
	if [ "x$?" == "x0" ]; then
		echog "Already redirect to ${log_path}."
	else
		sed -i 's@-l /var/log@-l '"${log_path}"'@' ${smb_script}
		grep -n "\-l ${log_path}" ${smb_script}
	fi

	setcfg global "log level"    10 -f ${smb_config}
	setcfg global "max log size"  0 -f ${smb_config}
#	setcfg global "log file"     "${log_path}/log.%m" -f ${smb_config}

	echoy "log.smbd debuglevel up."
	echoy "    log path     = ${log_path}"
	echoy "    log level    = 10"
	echoy "    max log size =  0 (unlimited)"
	${smb_script} restart

	echoy "log.nmbd debuglevel reset to 0 to save space."
	/usr/local/samba/bin/smbcontrol nmbd debug 0
	/usr/local/samba/bin/smbcontrol nmbd debuglevel
}

## Restore samba log to default path and restart samba.
## $1: working directory
samba_log_default()
{
	log_path=${1-/share/Public}
	smb_script="/etc/init.d/smb.sh"
	[ ! -d ${log_path} ] && echor "\"${log_path}\" no such directory, stopped." && return 1

	grep -n "\-l /var/log" ${smb_script}
	if [ "x$?" == "x0" ]; then
       		echog "Already default."
	else
		sed -i 's@-l '"${log_path}"'@-l /var/log@' ${smb_script}
		grep -n "\-l /var/log" ${smb_script}
	fi

	setcfg global -e "log level"       -f ${smb_config}
	setcfg global    "max log size" 10 -f ${smb_config}
#	setcfg global -e "log file"        -f ${smb_config}

	${smb_script} restart
}

case "$1" in
	redirect)
		samba_log_redirect
	;;
	default)
		samba_log_default
	;;
	*)
		echo "Usage: ${0} {redirect|default}"
		echo "Options:"
		echo "        redirect - redirect samba log to /share/Public and set 'log level = 10'"
		echo "                   /share/Public/log.smbd"
		echo "                   /share/Public/log.smbd.old"
		echo "                   /share/Public/log.nmbd"
		echo "                   /share/Public/log.nmbd.old"
		echo "        default  - put samba log to default /var/log and set 'log level = 0'"
		echo "                   /var/log/log.smbd"
		echo "                   /var/log/log.smbd.old"
		echo "                   /var/log/log.nmbd"
		echo "                   /var/log/log.nmbd.old"
	exit 1
esac
