#!/bin/sh
#
# This will prepare and begin operation of the "application" program(s).
#

# Splash.
#
echo "Executing /app/scripts/startup..."

# Not running anything...
# echo "Not initializing network or applications..."
# exit 0

rtc_count=$(dmesg | grep 'unable to open rtc device' | wc -l)
if [ "$rtc_count" = "1" ]
then
	sleep 5
	reboot
	sleep 2
fi

# Mount sysfs
mount -t sysfs sysfs /sys

# Mount usbfs
mount -t usbfs none /proc/bus/usb

# Source the port pin setup. This will be determined by hardware type.
# Any initialization specific to the hardware should be done there.
#
/app/scripts/gpio-setup

# Get push_button status status.
push_button_val=$(cat /sys/class/gpio/gpio46/value)

# If default pushbutton is low.
if [ "$push_button_val" = "0" ]
then
	echo "Default pushbutton pressed: setting default ip and passwords."
	#
	cd /app/config
	tar -xzf /scripts/recover-network.tgz
	cd -
	#
	cd /etc
	tar -xzf /scripts/recover-etc.tgz
	sleep 3
	cd -
	# Store new config so it's good for next boot.
	# Does nothing for JFFS2 file systems.
	/scripts/config_store
fi

haveged -w 2048 &
mkdir /tmp/genrsa
/app/scripts/certs.sh &

# Create config files from settings file
/app/bin/config-loader

# Bring up the network interface.
/scripts/network_up

# Start inetd.
inetd

# Start ssh, but first check if ssh keys exist, else create keys
if [ ! -e /etc/ssh/ssh_host_key ]
then
	ssh-keygen -A
fi

mkdir /var/run/sshd
/usr/sbin/sshd &

# Not running applications...
# echo "NOT running application"
# exit 0

# Common iptables settings
sleep 5
/scripts/iptables_Init2 > /dev/null 2>&1

# Start web server.
/usr/sbin/lighttpd -m /usr/lib/lighttpd -f /etc/lighttpd/lighttpd.conf &

# Monitor default push button
/app/scripts/resetIP.sh &

# Monitor Settings Change
/app/scripts/settingsChange &

. /app/config/network_wan.ini
if [ "$VPN_MASQ" = "YES" ]; then
	iptables -t nat -I POSTROUTING -o eth0 -j MASQUERADE
fi

# And exit.
exit 0
