#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1

SMB_CONF=""
BIND_IF_PARM=""
NB_PARM="$(cat /proc/sys/kernel/hostname)"
WG_PARM="WORKGROUP"
BI_PARM=""

start_service() {

	. /lib/functions/network.sh

	if [ -e /etc/ksmbd/smb.conf ] && [ -e /etc/init.d/ksmbd ] && /etc/init.d/ksmbd running; then
		SMB_CONF="/etc/ksmbd/smb.conf"
	fi

	[ -e /etc/samba/smb.conf ] && {
		if [ -e /etc/init.d/samba4 ] && /etc/init.d/samba4 running; then
			SMB_CONF="/etc/samba/smb.conf"
		elif [ -e /etc/init.d/samba ] && /etc/init.d/samba running; then
			SMB_CONF="/etc/samba/smb.conf"
		fi
	}

	[ -z "$SMB_CONF" ] && {
		logger -p daemon.error -t 'wsdd2' "samba36/4 or ksmbd is not running, can't start wsdd2!"
		exit 1
	}

	local nb_name
	nb_name="$(grep -i 'netbios name' $SMB_CONF | awk -F'=' '{print $2}' | tr -d ' \n')"
	[ -n "$nb_name" ] && NB_PARM="$nb_name"

	local wg_name
	wg_name="$(grep -i 'workgroup' $SMB_CONF | awk -F'=' '{print $2}' | tr -d ' \n')"
	[ -n "$wg_name" ] && WG_PARM="$wg_name"

	# resolve lan interface (BUG: No multi-interface binds atm)
	local ifname
	network_get_device ifname lan

	local board_vendor
	local board_model
	local board_sku

	[ -e /tmp/sysinfo/board_name ] && {
		board_vendor="$(awk -F',' '{print $1}' /tmp/sysinfo/board_name | tr ' ' '_' | tr -d ' \n')"
		board_sku="$(awk -F',' '{print $2}' /tmp/sysinfo/board_name | tr ' ' '_' | tr -d ' \n')"
	}

	[ -e /tmp/sysinfo/model ] && {
		board_model="$(awk -F':' '{print $1}' /tmp/sysinfo/model | tr ' ' '_' | tr -d ' \n')"
	}

	[ -n "$board_vendor" ] && [ -n "$board_model" ] && {
		if [ -n "$board_sku" ]; then
			BI_PARM="vendor:$board_vendor,model:$board_model,sku:$board_sku"
		else
			BI_PARM="vendor:$board_vendor,model:$board_model"
		fi
	}

	procd_open_instance
	procd_set_param command /usr/bin/wsdd2
	[ -n "$ifname" ] && procd_append_param command -i "$ifname"
	procd_append_param command -N "$NB_PARM"
	procd_append_param command -G "$WG_PARM"
	[ "x${BI_PARM}" = "x" ] || procd_append_param command -b "$BI_PARM"
	procd_set_param respawn
	procd_set_param file "$SMB_CONF"
	procd_close_instance
}

service_triggers() {
	PROCD_RELOAD_DELAY=1000
	procd_add_reload_trigger "dhcp" "system" "samba" "samba4" "ksmbd"
}
