#!/bin/sh

# (c) 2014-2015 Sam Nazarko
# email@samnazarko.co.uk

# Read /proc/cmdline arguments

for option in $(cat /proc/cmdline); do
	case $option in
	  osmcdev=*)
	    OPTION_OSMCDEV="${option#*=}"
	    ;;
	  root=UUID=*)
	    OPTION_UUID=$(echo "${option#root=UUID=*}" | sed 's/"//g')
	    ;;
	  root=*)
	    OPTION_ROOT=$(echo "${option#*=}" | sed 's/"//g')
	    ;;
	  nfsroot=*)
	    OPTION_FILESYSTEM="nfs"
	    ;;
	esac
done

if [ "$OPTION_UUID" ]; then OPTION_ROOT=$(blkid -U "$OPTION_UUID"); fi

# Set up swap file if required

MEMORY=$(cat /proc/meminfo | grep MemTotal | awk {'print $2'})

if [ -f /enable_swap ] || [ "$MEMORY" -lt 262144 ]
then
	if [ ! -f /swap ]
	then
		dd if=/dev/zero of=/swap bs=1M count=128
		chmod 0600 /swap
		mkswap /swap
	fi
	if [ "$OPTION_FILESYSTEM" = "nfs" ]
	then
		losetup /dev/loop0 /swap
		mkswap /dev/loop0
		swapon /dev/loop0
	else
		swapon /swap
	fi
fi

# Set readahead on non-rotational drives

if [ $(lsblk -n -d -o RM "$OPTION_ROOT") -eq 1 ] || [ $(lsblk -n -d -o ROTA "$OPTION_ROOT") -eq 0 ]
then
	LVMDEVICES=$(lsblk -n -o MAJ:MIN,TYPE -s "$OPTION_ROOT" | grep lvm | sed 's/[^0-9:]*//g')
	for LVMDEVICE in $LVMDEVICES; do
		echo 4096 > "/sys/dev/block/$LVMDEVICE/queue/read_ahead_kb"
	done
	DEVICES=$(lsblk -n -o MAJ:MIN,TYPE -s "$OPTION_ROOT" | grep disk | sed 's/[^0-9:]*//g')
	for DEVICE in $DEVICES; do
		echo 1024 > "/sys/dev/block/$DEVICE/queue/read_ahead_kb"
	done
fi

if [ "$OPTION_OSMCDEV" = "vero2" ] || [ "$OPTION_OSMCDEV" = "vero3" ]
then
     if grep -q 4kplus /proc/cmdline; then echo 5 > /sys/class/mpgpu/cur_freq; fi
     sleep 30
     fstrim -v /
fi

if [ ! -f /safe_mode ]
then
	# 30 seconds of accelerated boot. we set curgov to ondemand so the next check only doesn't flip us back if we had performance to begin with
	sleep 30
	echo "ondemand" | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor > /dev/null 2>&1 #all platforms
	else
		echo "powersave" | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor > /dev/null 2>&1
fi

exit 0
