#!/bin/sh

echo "booting anthillOS"

echo "stopping stock services"
killall -9 lighttpd || true
killall -9 syslogd || true
killall -9 daemons || true
killall -9 S52miner_act stop || true
killall -9 S71monitorcg stop || true
/etc/init.d/S70cgminer stop || true
/etc/init.d/S65monitor-ipsig stop || true
/etc/init.d/S66monitor-recobtn stop || true

# Remove stock files
rm -f /usr/bin/cgminer
rm -f /usr/bin/bmminer
rm -f /etc/init.d/S70cgminer || true
rm -f /etc/init.d/S65monitor-ipsig || true
rm -f /etc/init.d/S66monitor-recobtn || true
rm -f /etc/init.d/S52miner_act || true
rm -f /etc/init.d/S71monitorcg || true

echo "powering off"
if [ ! -d /sys/class/gpio/gpio412 ]; then
	echo 412 > /sys/class/gpio/export
	echo out > /sys/class/gpio/gpio412/direction
fi
echo "0" > /sys/class/gpio/gpio412/value

echo "resetting chains"
if [ ! -d /sys/class/gpio/gpio427/value ]; then
	echo 427 > /sys/class/gpio/export
	echo out > /sys/class/gpio/gpio427/direction
fi
echo "0" > /sys/class/gpio/gpio427/value

if [ ! -d /sys/class/gpio/gpio429/value ]; then
	echo 429 > /sys/class/gpio/export
	echo out > /sys/class/gpio/gpio429/direction
fi
echo "0" > /sys/class/gpio/gpio429/value

if [ ! -d /sys/class/gpio/gpio431/value ]; then
	echo 431 > /sys/class/gpio/export
	echo out > /sys/class/gpio/gpio431/direction
fi
echo "0" > /sys/class/gpio/gpio431/value

if [ ! -d /sys/class/gpio/gpio433/value ]; then
	echo 433 > /sys/class/gpio/export
	echo out > /sys/class/gpio/gpio433/direction
fi
echo "0" > /sys/class/gpio/gpio433/value

# Don't log exceptions into dmesg
echo "0" > /proc/sys/debug/exception-trace

echo "remounting config partition"

if [ ! -d /config-stock ]; then
	umount /config
	mkdir /config-stock
	mount -t ext4 -o sync /dev/mmcblk0p5 /config-stock
fi

mount --bind /nvdata/anthillos/config /config

echo "extracting overlay files"
tar -xzf /nvdata/anthillos/overlay.tar.gz -C /

# Restore config files
[ -e /config-stock/mac ] && ln -s /config-stock/mac /config/mac
[ -e /config-stock/network.conf ] && ln -s /config-stock/network.conf /config/network.conf
[ -e /config-stock/sn ] && ln -s /config-stock/sn /config/serial
/etc/init.d/S13restore start

# Restore shadow file
rm -f /etc/shadow
cp /etc/shadow.factory /etc/shadow

if lsmod | grep -q "uart_trans"; then
    rmmod uart_trans
fi

echo "starting anthill services"
/etc/init.d/S15timezone start
/etc/init.d/S12hwscan start
/etc/init.d/S80dashd start
/etc/init.d/S70miner start
/etc/init.d/S71monitor start
/etc/init.d/S50dropbear restart