#!/bin/sh
# Copyright (c) 2000-2014 Synology Inc. All rights reserved.

# linuxrc.syno will go into junior mode or active mode(mount md0 and switch_root) depend on the return value
# 0: active mode, 1: junior mode
# it will block in this script for passive mode

echo "START AHAtasks, action is '$1'"

. /etc.defaults/rc.subr

# adjust message queue
dual_head_adjust_msg_queue

TIME_TO_CHECK_IF_GO_INTO_NEXT_STAGE=1
DUAL_GLIBC_PATH=/dual_glibc
EXEC_BINARY="/usr/sbin/chroot $DUAL_GLIBC_PATH"
GO_INTO_ACTIVE_MODE=$DUAL_GLIBC_PATH/`$EXEC_BINARY /usr/syno/synoaha/bin/synoahastr --go-into-active-mode`
GO_INTO_JUNIOR_MODE=$DUAL_GLIBC_PATH/`$EXEC_BINARY /usr/syno/synoaha/bin/synoahastr --go-into-junior-mode`
REBOOT=$DUAL_GLIBC_PATH/`$EXEC_BINARY /usr/syno/synoaha/bin/synoahastr --reboot`
POWEROFF=$DUAL_GLIBC_PATH/`$EXEC_BINARY /usr/syno/synoaha/bin/synoahastr --poweroff`
NET_DRIVERS="dca e1000e i2c-algo-bit igb be2net ixgbe tn40xx"
SYNOBOOT3_MOUNT_POINT=/tmp/aha/synoboot3

##################################################
# Exit ret define
exit_become_active=0
exit_not_support_sas=1
exit_no_disks=2
exit_manufactory_dev_detected=3
exit_unknown_err=99
exit_go_into_junior_mode=100
exit_reboot=101
exit_poweroff=102
##################################################

##################################################
# stage
stage_check="check_stage"
stage_junior="junior_stage"
##################################################

mount_fs()
{
	[ -d $DUAL_GLIBC_PATH/dev ] || cp -r /dev/ $DUAL_GLIBC_PATH/
	rm -f $DUAL_GLIBC_PATH/dev/log
	cp -rf /etc/* $DUAL_GLIBC_PATH/etc/
	[ -L $DUAL_GLIBC_PATH/etc.defaults ] || ln -s /etc $DUAL_GLIBC_PATH/etc.defaults
	if [ -d $DUAL_GLIBC_PATH/usr/lib ]; then
		mv -f $DUAL_GLIBC_PATH/usr/lib/* $DUAL_GLIBC_PATH/lib/
		rm -rf $DUAL_GLIBC_PATH/usr/lib
	fi
	[ -L $DUAL_GLIBC_PATH/usr/lib ] || ln -sf ../lib/ $DUAL_GLIBC_PATH/usr/lib
	[ -d $DUAL_GLIBC_PATH/proc ] || mkdir $DUAL_GLIBC_PATH/proc
	[ -d $DUAL_GLIBC_PATH/sys ] || mkdir $DUAL_GLIBC_PATH/sys
	[ -d $DUAL_GLIBC_PATH/tmp ] || mkdir $DUAL_GLIBC_PATH/tmp
	[ -d $DUAL_GLIBC_PATH/run ] || mkdir $DUAL_GLIBC_PATH/run
	[ -d $DUAL_GLIBC_PATH/mnt ] || mkdir $DUAL_GLIBC_PATH/mnt
	mount -t proc $DUAL_GLIBC_PATH/proc $DUAL_GLIBC_PATH/proc
	mount -t sysfs $DUAL_GLIBC_PATH/sys $DUAL_GLIBC_PATH/sys
	# FIXME: save log into synoboot3, should be remove afterwards
	$EXEC_BINARY mkdir -p $SYNOBOOT3_MOUNT_POINT
	$EXEC_BINARY echo 1 > /proc/sys/kernel/syno_install_flag
	$EXEC_BINARY mount /dev/synoboot3 $SYNOBOOT3_MOUNT_POINT
	$EXEC_BINARY touch $SYNOBOOT3_MOUNT_POINT/messages
	$EXEC_BINARY mkdir -p /var/log
	$EXEC_BINARY ln -s $SYNOBOOT3_MOUNT_POINT/messages /var/log/messages
}

umount_fs()
{
	umount $DUAL_GLIBC_PATH/sys
	umount $DUAL_GLIBC_PATH/proc
	# FIXME: save log into synoboot3, should be remove afterwards
	$EXEC_BINARY umount $SYNOBOOT3_MOUNT_POINT
}

load_necessary_module()
{
	SYNOLoadModules synobios sg usb-storage
}

unload_necessary_module()
{
	SYNOUnloadModules usb-storage sg
	if [ $exit_reboot -ne $1 -a $exit_poweroff -ne $1 ]; then
		# for reboot or powerof, it needs synobios to finish task
		# no need to unload synobios
		/sbin/rmmod `/sbin/lsmod | /usr/bin/cut -f 1 -d ' ' | /bin/grep synobios`
	fi
}

network_start()
{
	SYNOLoadModules ${NET_DRIVERS}
	/etc/rc.network start
}

network_stop()
{
	/etc/rc.network stop
	SYNOUnloadModules ${NET_DRIVERS}
}

necessary_daemon_start()
{
	$EXEC_BINARY /usr/bin/syslog-ng -F --worker-threads=`grep -c '^[Pp]rocessor' /proc/cpuinfo` &
	if [ $stage_check = $1 ]; then
		/sbin/syslogd -S
		/sbin/klogd
		/sbin/getty 115200 console &
		# start udevd
		# FIXME: copy from udevd.upstart
		$EXEC_BINARY /usr/bin/udevadm hwdb --update
		$EXEC_BINARY /lib/udev/script/syno_default_env.sh gen-rule-file
		$EXEC_BINARY /usr/bin/udevd --daemon
	fi
	# let host control enc power
	echo 1 > /proc/sys/kernel/syno_enc_pwr_ctl
	# end of start udevd
	echo "Starting to run HA manager"
	$EXEC_BINARY /usr/syno/synoaha/bin/syno_aha_mgr_daemon $1 &
}

necessary_daemon_stop()
{
	killall syno_aha_mgr_daemon
	killall syno_aha_comm_to_remote_daemon
	killall udevd
	killall syslog-ng
	killall getty
	killall klogd
	killall syslogd
}

Exit()
{
	if [ -n "$2" ]; then
		echo "Exit on error [$1] $2..."
	fi

	if [ $exit_become_active -eq $1 ]; then
		Ret=0
	else
		Ret=1
	fi

	# clear process and data
	necessary_daemon_stop
	sync
	umount_fs
	unload_necessary_module $1
	network_stop

	if [ $exit_reboot -eq $1 ]; then
		umount /sys
		umount /proc
		/sbin/reboot -f
		sleep 600
	elif [ $exit_poweroff -eq $1 ]; then
		umount /sys
		umount /proc
		/sbin/poweroff -f
		sleep 600
	fi

	exit $Ret
}

check_stage()
{
	# network start
	network_start
	# load the necessary kernel modules
	load_necessary_module

	SupportSAS=`/bin/get_key_value /etc.defaults/synoinfo.conf supportsas`
	if [ "$SupportSAS" = "yes" ]; then
		SYNOGenAllDeviceNodes
	else
		Exit $exit_not_support_sas "This model is not supported sas"
	fi

	# should be called after SYNOGenAllDeviceNodes
	mount_fs

	if [ "x" = "x`/usr/syno/bin/synodiskport -eunit 2>/dev/null`" ]; then
		touch /.nodisk
		Exit $exit_no_disks "DISK NOT INSTALLED"
	fi

	if detect_manufactory_device; then
		Exit $exit_manufactory_dev_detected "Manufactory device detected."
	fi

	necessary_daemon_start $stage_check

	while [ 1 ]; do
		if [ -f "$GO_INTO_ACTIVE_MODE" ]; then
			/bin/rm -f $GO_INTO_ACTIVE_MODE
			Exit $exit_become_active "======= Now try to become active..."
		elif [ -f "$GO_INTO_JUNIOR_MODE" ]; then
			/bin/rm -f $GO_INTO_JUNIOR_MODE
			Exit $exit_go_into_junior_mode "======= Now go into junior mode"
		elif [ -f "$REBOOT" ]; then
			/bin/rm -f $REBOOT
			Exit $exit_reboot "======= Now reboot"
		elif [ -f "$POWEROFF" ]; then
			/bin/rm -f $POWEROFF
			Exit $exit_poweroff "======= Now poweroff"
		fi
		sleep $TIME_TO_CHECK_IF_GO_INTO_NEXT_STAGE
	done


	Exit $exit_unknown_err "Unknown error"
}

junior_stage()
{
	mount_fs
	necessary_daemon_start $stage_junior
}

junior_monitor_reboot_or_poweroff()
{
	while [ 1 ]; do
		if [ -f "$REBOOT" -o -f "$POWEROFF" ]; then
			necessary_daemon_stop
			sync
			umount_fs
#			umount /sys
#			umount /proc
			if [ -f "$REBOOT" ]; then
				echo "============ AHA: now reboot ============" > /dev/console
				/bin/rm -f $REBOOT
#				/sbin/reboot -f
				/sbin/reboot
			elif [ -f "$POWEROFF" ]; then
				echo "============ AHA: now poweroff ============" > /dev/console
				/bin/rm -f $POWEROFF
#				/sbin/poweroff -f
				/sbin/poweroff
			fi
			sleep 600
		fi
		sleep 2
	done
}

action=$1;
shift

case "$action" in
	check_stage)
		check_stage
		;;
	junior_stage)
		junior_stage
		;;
	junior_monitor_reboot_or_poweroff)
		junior_monitor_reboot_or_poweroff
		;;
	*)
		echo "usage: {check_stage|junior_stage|junior_monitor_reboot_or_poweroff}"
		Exit $exit_unknown_err "Unknown error"
		;;
esac
