#!/usr/bin/env bash
# This file is part of the OpenADK project. OpenADK is copyrighted
# material, please see the LICENCE file in the top-level directory.

topdir=$(readlink -nf $(dirname $0)/.. 2>/dev/null || (cd $(dirname $0)/..; pwd -P))
. $topdir/.config

suffix=${ADK_TARGET_SYSTEM}_${ADK_TARGET_LIBC}_${ADK_TARGET_CPU_ARCH}
if [ ! -z ${ADK_TARGET_FLOAT} ];then
	suffix=${suffix}_${ADK_TARGET_FLOAT}
fi
if [ ! -z ${ADK_TARGET_ABI} ];then
	suffix=${suffix}_${ADK_TARGET_ABI}
fi
if [ -z ${ADK_TARGET_WITH_MMU} ];then
	suffix=${suffix}_nommu
fi

rcconf=$(ls $topdir/root_${suffix}/etc/rc.conf)

if [ ! -f $rcconf ];then
	exit 0
fi

for service in $(grep ^ADK_RUNTIME_START_ $topdir/.config |grep -v ADK_RUNTIME_START_SERVICES);do
	rcname=$(echo $service|sed -e "s#ADK_RUNTIME_START_##")
	rcname=$(echo $rcname| sed -e "s#=y##")
	rcname=$(echo $rcname| sed -e "s#^BUSYBOX_##")
	rcname=$(echo $rcname| tr '[:upper:]' '[:lower:]')
	# workarounds where package name not equal to service name
	if [ $rcname = "alsa_utils" ];then
		rcname=amixer
	fi
	if [ $rcname = "iptables" ];then
		rcname=firewall
	fi
	if [ $rcname = "openssh_server" ];then
		rcname=openssh
	fi
	if [ "$ADK_APPLIANCE_KODI" = "y" -o "$ADK_APPLIANCE_MPD" = "y" ];then
		sed -i -e "s#$rcname=\"NO\"#$rcname=\"DAEMON\"#" $rcconf
	else
		sed -i -e "s#$rcname=\"NO\"#$rcname=\"YES\"#" $rcconf
	fi
done
