#!/bin/sh -e

for patch in *.patch; do
    patch -p1 < "$patch"
done

# Remove forced gcc/g++ usage so builds work on gcc-less systems.
sed -i "s#= g[c+][c+]#= ${CC:=cc}#g" Makefile
sed -i "s#\(\$(CROSS_COMPILE)\)gcc#\1${CC}#g" Makefile

# Ensure that busybox's build system is aware that 'cc' may point
# to clang rather than GCC. This is the case in non-GCC systems.
case $("$CC" --version) in (*clang*)
    sed -i "s&\(\$(CC),\)clang&\1${CC}&g" Makefile.flags
esac

# Build and install regular busybox.
# This excludes utilities which require 'suid' to function.
cp -f config .config
make CC="$CC" HOSTCC="$CC"
make CONFIG_PREFIX="$1/usr" install

# Rename the binary temporarily.
mv "$1/usr/bin/busybox" "$1/usr/bin/busybox-nosuid"

# Build and install suid busybox.
# This _only_ includes utlities which require 'suid' to function.
cp -f config-suid .config
make CC="$CC" HOSTCC="$CC"
make CONFIG_PREFIX="$1/usr" install

# Aptly name the busybox binaries.
mv -f "$1/usr/bin/busybox"        "$1/usr/bin/busybox-suid"
mv -f "$1/usr/bin/busybox-nosuid" "$1/usr/bin/busybox"

# Install the non-suid symlinks.
"$1/usr/bin/busybox" --list | while read -r bin; do
    ln -s busybox "$1/usr/bin/$bin"
done

# Install the suid symlinks.
"$1/usr/bin/busybox-suid" --list | while read -r bin; do
    ln -s busybox-suid "$1/usr/bin/$bin"
done

# Set suid on busybox suid.
chmod u+s "$1/usr/bin/busybox-suid"

# Install runit services.
install -Dm755 crond.run           "$1/etc/sv/crond/run"
install -Dm755 syslogd.run         "$1/etc/sv/syslogd/run"
install -Dm755 mdev.run            "$1/etc/sv/mdev/run"
install -Dm755 ntpd.run            "$1/etc/sv/ntpd/run"
ln -s /run/runit/supervise.crond   "$1/etc/sv/crond/supervise"
ln -s /run/runit/supervise.syslogd "$1/etc/sv/syslogd/supervise"
ln -s /run/runit/supervise.mdev    "$1/etc/sv/mdev/supervise"
ln -s /run/runit/supervise.ntpd    "$1/etc/sv/ntpd/supervise"

install -Dm644 mdev.conf "$1/etc/mdev.conf"
install -Dm644 docs/busybox.1 "$1/usr/share/man/man1/busybox.1"
