#!/bin/bash
#
# 	DESCRIPTION:	this script use for system autoboot services.
#					function:
#					1.make a sysmbol link to script of autotboot services,
#					2.generate $pkgname-serv.conf, this configure file use by post_add.
#
#	Usage: echo "netkit-base inetd rsh S310"|./mk_serv_autoboot.sh
#
#	SCRIPT NAME:	mk_serv_autoboot.sh
#
#	Input:	stdin
#			1. package name of autoboot services
#			2. boot script
#			3. boot service
#			4. boot number
#
#	Output:	
#			NULL
#	Return value:
#			1 argument error
#			2 boot script doesn't exist
#
#	AUTHOR:		Qin Bo
#
#	EMAIL:		bqin@linx-info.com
#
#	DATE:		2010-08-23
#
#	HISTORY:
#	REVISOR		DATE			MODIFICATION
#	Qin Bo		2010-08-23		create
#
#
#

source ./functions

make_sysmbol_link ()
{

	if [ $# -ne 2 ];then
		err "$FUNCNAME function argument error, it must have 2 argument!"
		return 1
	fi

	local script="$1"
	local number="$2"

	for dir in $RC_DIR; do
		pushd $dir >>$DEV_LOG &&
		if [ -e $INIT_DIR/$script ];then
			if [ -L "$dir/$number$script" ];then
				# may be the symbol link has already exist, skip it,
				# mulit-services, may have common script to boot it. 
				# ex: rsh and rlogin service start through inetd script.
				:
			else
				ln -sf ../init.d/$script ./$number$script
			fi
		else
			err "$script doesn't exist in $INIT_DIR"
			return 2
		fi    
		popd >>$DEV_LOG
	done

}

# generate $pkgname-serv.conf, use by $pkgname.post_add
gen_serv_cnf ()
{
	if [ $# -ne 2 ];then
		err "$FUNCNAME function argument error, it must have 2 argument!"
		return 1
	fi

	local pkgname="$1"	
	local service="$2"

	# may be some boot services needn't configure, 
	# it also generate pkgname-serv.conf.
	# ex: at service, if it need autoboot, 
	# it also generate at-serv.conf, although it needn't configure.
	if [  -e "$SERV_CFG_DIR/$pkgname-serv.conf" ];then
		# to avoid duplicate-line in $pkgname-serv.conf, we only append it when $service=yes 
		# not exist in $pkgname-serv.conf
		if [ -z "$(grep "$service=yes" "$SERV_CFG_DIR/$pkgname-serv.conf")" ];then
			printf "%s=yes\n" $service >> "$SERV_CFG_DIR"/"$pkgname-serv.conf"
		fi
	else
		printf "%s=yes\n" $service > "$SERV_CFG_DIR"/"$pkgname-serv.conf"
	fi

}


mk_serv_autoboot ()
{
	
	local pkgname="$1"
	local script="$2"
	local service="$3"
	local number="$4"

	make_sysmbol_link "$script" "$number"
	erv
	gen_serv_cnf "$pkgname" "$service"
	erv

}

main ()
{
	local line

	info "configure auto boot service"
	while read line;do
		if [ -n "$line" ];then
			mk_serv_autoboot $line
			erv
		fi
	done
	info "configure auto boot service success"
}


RCD="$TARGET/etc/rc.d"
INIT_DIR="$RCD/init.d"
# according old Rocky installer, make symbol link in rc3.d and rc5.d
RC_DIR="$RCD/rc3.d $RCD/rc5.d"
SERV_CFG_DIR="$TARGET/var/lib/pkg"

main "$@"


