#!/bin/bash
#lrrr@armbian.com
#
## customize-image.sh script to remove systemd

# remove systemd
REMOVE_SYSTEMD="yes"

# build variables
RELEASE=$1
LINUXFAMILY=$2
BOARD=$3
BUILD_DESKTOP=$4

source /etc/armbian-image-release

# main
Main() {
	if [[ $REMOVE_SYSTEMD == yes ]]; then
		WithoutSystemd
	elif [[ $RELEASE == stretch && $BRANCH == default ]]; then
		systemctl --no-reload disable systemd-timesyncd.service >/dev/null 2>&1
	fi

	# uncomment optional tweak example for noop queue for mmc
	# optimization_tweak
}

# http://without-systemd.org
WithoutSystemd() {
	local packages="sysvinit-core"
	if [[ $RELEASE == jessie ]]; then
		packages="$packages sysvinit-utils"
	fi

	# remove systemd
	systemctl --no-reload disable firstrun.service resize2fs.service armhwinfo.service log2ram.service firstrun-config.service
	apt-get remove --purge --auto-remove --yes systemd

	# add sysvinit
	apt-get install --yes $packages
	cp -p /usr/share/sysvinit/inittab /etc/inittab
	printf "Package: *systemd*\nPin: release *\nPin-Priority: -1\n" > /etc/apt/preferences.d/nosystemd
	insserv

	sed -i 's#\#T0:23:respawn:/sbin/getty -L ttyS0 9600 vt100#T0:23:respawn:/sbin/getty -L ttyS0 115200 vt100#' /etc/inittab
}

# optional tweak example based on bsp armbian-hardware-optimization
optimization_tweak() {
	local file="/etc/rc.local"
	if [[ ! -f $file ]]; then
		return
	fi

	sed -i 's/^exit 0$//' $file

	printf '# set mmc scheduler to noop\n' >> $file
	printf 'set_io_scheduler() {\n' >> $file
	printf '\tif [ -f /sys/block/mmcblk0/queue/scheduler ]; then\n' >> $file
	printf '\t\t/bin/echo noop > /sys/block/mmcblk0/queue/scheduler\n' >> $file
	printf '\tfi\n' >> $file
	printf '}\n' >> $file
	printf 'set_io_scheduler\n' >> $file
	printf 'exit 0\n' >> $file
}

Main "$@"
