#!/bin/sh
#
# Copyright (c) 2019 David Demelier <markand@malikania.fr>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

PKGNAME=busybox
PKGVERSION=1.30.1
PKGREVISION=1
PKGLICENSE="GPLv2"
PKGSUMMARY="swiss army knife for embedded"
PKGDOWNLOAD="https://busybox.net/downloads/$PKGNAME-$PKGVERSION.tar.bz2"
PKGOPTIONS="CONFIG IPV6 PAM SELINUX"
PKGPROTECT="etc/udhcpd.conf"

: ${CC:=clang}
: ${CFLAGS:=-O2}
: ${LDFLAGS:=}
: ${CONFIG:=}
: ${IPV6:=yes}
: ${SELINUX:=no}
: ${PAM:=no}

build()
{
	rm -rf $PKGNAME-$PKGVERSION
	tar xvf $PKGNAME-$PKGVERSION.tar.bz2
	cd $PKGNAME-$PKGVERSION

	#
	# Allow user to specify a full config if specified, otherwise change
	# package options.
	#
	if [ -n "$CONFIG" ] && [ -r "$CONFIG" ]; then
		cp $CONFIG .config

		#
		# When specifying a config file, force other selective options
		# to a dummy value to avoid incorrect information in package
		# file.
		#
		IPV6=""
		SELINUX=""
		PAM=""
	else
		cp ../config .config

		if [ "$SELINUX" = "yes" ]; then
			echo "CONFIG_SELINUX=y" >> .config
			echo "CONFIG_FEATURE_TAR_SELINUX=y" >> .config
			echo "CONFIG_SELINUXENABLED=y" >> .config
		fi

		if [ "$PAM" = "yes" ]; then
			echo "CONFIG_PAM=y" >> .config
		fi

		if [ "$IPV6" != "yes" ]; then
			sed -i -e "/CONFIG_FEATURE_IPV6=y/ s/y/n/" .config
			sed -i -e "/CONFIG_FEATURE_IFUPDOWN_IPV6=y/ s/y/n/" .config
		fi
	fi

	# Our start script is located in /etc/rc.init.
	sed -i -e 's|/etc/init.d/rcS|/etc/rc.init|' init/init.c

	make CC="$CC" HOSTCC="$CC" CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS"
	install -Dm0755 busybox $DESTDIR/bin/busybox
	install -dm0755 $DESTDIR/share/udhcp
	install -m0644 examples/udhcp/sample.* $DESTDIR/share/udhcp
	install -Dm0644 examples/udhcp/udhcpd.conf $DESTDIR/etc/udhcpd.conf
	install -Dm0644 ../busybox.crond $DESTDIR/etc/rc.d/busybox.crond
	install -Dm0644 ../busybox.klogd $DESTDIR/etc/rc.d/busybox.klogd
	install -Dm0644 ../busybox.mdev $DESTDIR/etc/rc.d/busybox.mdev
	install -Dm0644 ../busybox.syslogd $DESTDIR/etc/rc.d/busybox.syslogd

	cd ..
	rm -rf $PKGNAME-$PKGVERSION
}
