#!/bin/ash

tweak_system() {
	#system startup tweaking
	touch /mnt/etc/fastboot
	sed -e 's@^\(/bin/rm -f /etc/mtab.*\)$@#\1@' -i /mnt/etc/rc.d/rc.S
	if [ "$mediadetected" = "nfs" ] && [ -x /mnt/etc/rc.d/rc.networkmanager ]; then 
		chmod -x /mnt/etc/rc.d/rc.networkmanager #if enabled, system hangs
		echo "Hidden=true" >> /mnt/etc/xdg/autostart/nm-applet.desktop
	fi

	#system shutdown tweaking
	sed 's/\(\/rc.[06]\)\( fast\)*/\1 fast/' -i /mnt/etc/inittab #to prevent system hang at shutdown
	if [ "$mediadetected" = "nfs" ]; then
		sed -e 's@^\( *\)\([a-z/]*fuser -k.*\)@\1: #\2@' \
			-e 's@^\( *\)\([a-z/]*dhcpcd -k.*\)@\1: #\2@' \
			-e 's@^\( *\)\(\. /etc/rc\.d/rc\.inet1 stop\)@\1: #\2@' \
			-e 's@-t \(nfs,\)\(.*\)@-t \2 #\1@' \
			-i /mnt/etc/rc.d/rc.6
	fi
	if [ "$mediadetected" = "cd" ]; then
		sed	-e "s@\(/sbin/reboot\)@reboot -w; shutdown -k now \>/dev/null\n  cdrecord --eject dev=$livedevice \>/dev/null 2\>\&1\n  sleep 5\n  \1@" \
			-e "s@\(/sbin/poweroff\)@poweroff -w; shutdown -k now \>/dev/null\n  cdrecord --eject dev=$livedevice \>/dev/null 2\>\&1\n  sleep 5\n  \1@" \
			-i /mnt/etc/rc.d/rc.6
	fi
	if [ "$mediadetected" = "sd" ]; then
		sed 's@\(/sbin/telinit u\)@\1\n\nfor u in `grep ":/home" /etc/passwd | cut -f1 -d:`; do\n\tkillall -u $u;\ndone\nsync; sleep 5; mount -o remount,ro /home@' -i /mnt/etc/rc.d/rc.6
	fi
}

enable_persistent_wifi() {
	echo -e "PATH=/usr/sbin:/sbin:/usr/bin:/bin\n/usr/local/bin/live-system-wifi.sh start" >> /mnt/etc/rc.d/rc.local
	chmod +x /mnt/etc/rc.d/rc.local
	
	if [ ! -f /mnt/etc/rc.d/rc.local_shutdown ]; then
		echo -e '#!/bin/bash\nPATH=/usr/sbin:/sbin:/usr/bin:/bin' > /mnt/etc/rc.d/rc.local_shutdown
	fi
	echo -e "mount -o remount,rw /home\nlive-system-wifi.sh stop\nmount -o remount,ro /home" >> /mnt/etc/rc.d/rc.local_shutdown
	chmod +x /mnt/etc/rc.d/rc.local_shutdown
}

setup_locale() {
	if [ ! -z "$locale" ]; then
		echo "Setting up locale ($locale)"
		if [ -f /mnt/etc/profile.d/lang.sh ] && grep -q "^export LANG=" /mnt/etc/profile.d/lang.sh
		then sed s/^export\ LANG=.*/export\ LANG=$locale/ -i /mnt/etc/profile.d/lang.sh
		else echo "export LANG=$locale" >> /mnt/etc/profile.d/lang.sh
		fi
	fi
}

setup_time() {
	if [ ! -z "$tz" ]; then
		if [ -f /mnt/usr/share/zoneinfo/$tz ]; then
			echo "Setting up timezone ($tz)"
			cat /mnt/usr/share/zoneinfo/$tz > /mnt/etc/localtime
			ln -sf /usr/share/zoneinfo/$tz /mnt/etc/localtime-copied-from
		fi
	fi
	if [ ! -z "$hwc" ]; then
		if [ "$hwc" = "UTC" ] || [ "$hwc" = "localtime" ]; then
			echo "Setting up hardware clock ($hwc)"
			echo "$hwc" > /mnt/etc/hardwareclock
		fi
	fi
}

setup_console_keymap() {
	if [ ! -z "$keymap" ]; then
		echo "Setting up keymap ($keymap)"
		cat > /mnt/etc/rc.d/rc.keymap <<END
#!/bin/sh
if [ -x /usr/bin/loadkeys ]; then
	/usr/bin/loadkeys $keymap
fi
END
		chmod +x /mnt/etc/rc.d/rc.keymap
	fi
}
