#!/usr/bin/env bash

# Usage:       ./cross_build_static_busybox_for_arm
#                or
#              bash cross_build_static_busybox_for_arm
# Description: Download newest stable busybox release and
#                compiles a static binary for arm
# Author:      Patrick Neumann (patrick@neumannsland.de)
# Platform:    Debian or Raspbian GNU/Linux (tested: 9.5)
# Version:     1.0
# Date:        06.07.2018
# License:     GPL3
# Warranty:    This program is distributed WITHOUT ANY WARRANTY

# autodetect release or do it manualy:
RELEASE="$( /usr/bin/curl --silent https://busybox.net/ \
            | /bin/grep --extended-regexp "BusyBox [[:digit:]]\.[[:digit:]]{1,2}\.[[:digit:]]{1,2} \(stable\)" \
            | /usr/bin/head --lines=1 \
            | /bin/grep --extended-regexp --only-matching "[[:digit:]]\.[[:digit:]]{1,2}\.[[:digit:]]{1,2}" )"
#RELEASE="1.29.2"
/usr/bin/test -n "${RELEASE}" || ( echo "Release detection failed - please edit script manually" ; exit 1 )

# dependencies:
/usr/bin/sudo /usr/bin/apt install gcc-arm-linux-gnueabihf libncurses5 libncurses5-dev --assume-yes

# downloading...
/usr/bin/wget http://busybox.net/downloads/busybox-${RELEASE}.tar.bz2

# extracting...
/bin/tar xjf busybox-${RELEASE}.tar.bz2 

# compiling (and stripping)...
cd busybox-${RELEASE}/
/usr/bin/make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- defconfig
/bin/sed --expression='s/.*FEATURE_PREFER_APPLETS.*/CONFIG_FEATURE_PREFER_APPLETS=y/' --in-place .config
/bin/sed --expression='s/.*FEATURE_SH_STANDALONE.*/CONFIG_FEATURE_SH_STANDALONE=y/' --in-place .config
/bin/sed --expression='s/.*FEATURE_EDITING_SAVEHISTORY.*/# CONFIG_FEATURE_EDITING_SAVEHISTORY is not set/' --in-place .config
/bin/sed --expression='s/.*CONFIG_STATIC.*/CONFIG_STATIC=y/' --in-place .config
/usr/bin/make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-

# rename binary:
BINARY="busybox-arm-${RELEASE}"
/bin/mv busybox "${BINARY}"

# final instructions:
echo
echo "Ready to copy:"
echo
echo "  cp ${PWD}/${BINARY} /media/POLICE/"
echo

exit 0