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

HOME=/
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/syno/sbin:/usr/syno/bin:/usr/local/sbin:/usr/local/bin
export HOME PATH

mount -o remount,rw /dev/root /
SupportPORTMAPV2=`/bin/get_key_value /etc.defaults/synoinfo.conf supportportmappingv2`
if [ "$SupportPORTMAPV2" = "yes" ]; then
	cp -vf /etc.defaults/model.dtb /var/run/
fi

. /etc.defaults/rc.subr
. /etc.defaults/rc.fan
. /etc.defaults/rc.wifi

SYNOINFO="/etc/synoinfo.conf"
SYNOINFO_DEF="/etc.defaults/synoinfo.conf"
KERNEL_VCODE=`KernelVersionCode $(KernelVersion)`

UNIQUE=`get_key_value $SYNOINFO_DEF unique`
PLATFORM=`get_key_value $SYNOINFO_DEF unique | cut -d"_" -f2`
MODEL=`get_key_value $SYNOINFO_DEF unique | cut -d"_" -f3`
IPv4_ONLY=`get_key_value $SYNOINFO_DEF ipv4only`
CONFIGURED=`get_key_value $SYNOINFO configured`
MIN_FREE_KBYTES=`get_key_value $SYNOINFO_DEF min_free_kbytes`

SUPPORT_DUAL_HEAD=`/bin/get_key_value /etc.defaults/synoinfo.conf support_dual_head`
SUPPORT_RAID=`get_key_value $SYNOINFO_DEF supportraid`
SUPPORT_STARTUPD=`get_key_value $SYNOINFO_DEF supportstartupd`
SUPPORT_HDD_DYNAMIC_POWER=`get_key_value $SYNOINFO_DEF HddEnableDynamicPower`
SUPPORT_LOCALINSTALL=`get_key_value $SYNOINFO_DEF support_localinstall`
SupportPortMappingV2=`get_key_value /etc.defaults/synoinfo.conf supportportmappingv2`

RUN_SYNOBIOS=`get_key_value $SYNOINFO synobios`
SupportSAS=`/bin/get_key_value /etc.defaults/synoinfo.conf supportsas`
SUPPORT_BDE_10G=`/bin/get_key_value /etc.defaults/synoinfo.conf support_bde_internal_10g`

if [ "yes" = "${SUPPORT_DUAL_HEAD}" ]; then
	. /etc/rc.network_dualhead
fi

RCMsg "Starting /etc/rc"
RCMsg "Mounting procfs" \
mount -n -t proc /proc /proc
grep /dev/root /proc/mounts > /etc/mtab
rm -rf /var/tmp  /var/state/ups/*
ln -s /tmp /var/tmp

RCMsg "Mounting tmpfs" \
mount -t tmpfs /tmp /tmp

RCMsg "Mounting devtmpfs" \
mount -t devtmpfs none /dev

RCMsg "Mounting devpts" \
mkdir -p /dev/pts
mount -vt devpts -o gid=4,mode=620 none /dev/pts

# for device node autogen
if [ $KERNEL_VCODE -ge $(KernelVersionCode "2.6") ]; then
	RCMsg "Mounting sysfs" \
	mount -t sysfs /sys /sys
fi

if [ "$SupportSAS" = "yes" ]; then
	. /etc.defaults/rc.sas
	SASEnablePhy
fi

SYNOLoadIPv6()
{
	# see bug 16542, some modules of 824x don't support ipv6
	# fixed by add this key to minimize the effect
	local v6install=`get_key_value $SYNOINFO_DEF v6install`
	# check if ipv4 only platform...
	if [ "$IPv4_ONLY" = "yes" ]; then
		# ipv4 only platform but forced to install v6 module..
		if [ "$v6install" = "yes" ]; then
			SYNOLoadModules "ipv6"
		fi
		return
	fi
	SYNOLoadModules "ipv6"
}


SYNOLoadLED_lp3943()
{
	local supportlp3943=`get_key_value $SYNOINFO_DEF support_leds_lp3943`

	if [ "$supportlp3943" = "yes" ]; then
			SYNOLoadModules i2c-i801 leds-lp3943
	fi
}

# On dualhead model, junior should not take the swap.
if [ "yes" != "$SUPPORT_DUAL_HEAD" ]; then
	# turn swap on
	if [ "$SUPPORT_RAID" = "yes" ]; then
		SwapDevice="/dev/md1"
		CheckSwapRaid
		if [ "$?" = "1" ]; then
			mdadm -S $SwapDevice
			MkSwapRaid 1
		fi
	else
		if [ "${SupportPortMappingV2}" = "yes" ]; then
			SwapDevice="/dev/sata1p2"
		else
			SwapDevice="/dev/sda2"
		fi
	fi

	swapon $SwapDevice
fi

# Set the host name
HOSTNAME=`get_key_value $SYNOINFO hostname`
hostname ${HOSTNAME}

ThisMachine=`uname -m`
if [ $KERNEL_VCODE -ge $(KernelVersionCode "2.6") ]; then
	# 2.6 or 3.x
	VXLAN_MODULES="ip_tunnel udp_tunnel ip6_udp_tunnel vxlan"
	NET_DRIVERS="${VXLAN_MODULES} dca e1000e i2c-algo-bit igb be2net ixgbe r8168"
	if [ "kvmx64" == "$PLATFORM" -o "nextkvmx64" == "$PLATFORM" ]; then
		NET_DRIVERS="${VXLAN_MODULES} igbvf be2net ixgbevf i40evf"
	fi
	CRYPTO_MODULES="crypto_algapi crypto_wq crypto_blkcipher crypto_hash aead pcompress cryptomgr cbc md5 aes_generic rng cts ansi_cprng krng eseqiv crc32c des_generic chainiv ocf cryptodev rng-core authenc talitos cesa_dev cesa_ocf_drv aes-x86_64 aes-i586 ecb sha1_generic sha256_generic ecryptfs cryptosoft cryptd aesni-intel"
	RAID_MODULES="dm-mod async_tx async_memcpy xor async_xor raid6_pq async_pq async_raid6_recov linear raid0 raid10 raid456"
	if [ $KERNEL_VCODE -ge $(KernelVersionCode "4.4") ]; then
		KERNEL_MODULES="llc p8022 psnap sg usbcore quota_tree quota_v2 crc-ccitt crc-itu-t zlib_inflate dm-bufio dm-snapshot freq_table cpufreq_stats cpufreq thermal_sys processor mperf acpi-cpufreq cpufreq_ondemand cpufreq_performance cpufreq_powersave cpufreq_conservative mdio"
	else
		KERNEL_MODULES="llc p8022 psnap sg usbcore quota_tree quota_v2 crc-ccitt crc-itu-t zlib_inflate dm-snapshot freq_table cpufreq_stats cpufreq thermal_sys processor mperf acpi-cpufreq cpufreq_ondemand cpufreq_performance cpufreq_powersave cpufreq_conservative mdio"
	fi
	KERNEL_I2C_MODLES="i2c-core of_i2c i2c-mpc"
	if [ "ppc853x" = "$PLATFORM" ]; then
		KERNEL_MODULES="${RAID_MODULES} ${KERNEL_MODULES} ${CRYPTO_MODULES} ${KERNEL_I2C_MODLES}"
	elif [ "comcerto2k" = "$PLATFORM" ]; then
		KERNEL_MODULES="xor-neon ${RAID_MODULES} ${KERNEL_MODULES} ${CRYPTO_MODULES}"
	else
		KERNEL_MODULES="${KERNEL_MODULES} ${CRYPTO_MODULES}"
	fi
	KERNEL_MODULES="${KERNEL_MODULES} fat vfat fuse"
	if [ $KERNEL_VCODE -ge $(KernelVersionCode "3") ]; then
	# 3.x
		KERNEL_MODULES="${KERNEL_MODULES} ${NET_DRIVERS}"
		KERNEL_MODULES="usb-common ${KERNEL_MODULES} hmac md4 hfsplus crc32c libcrc32c zlib_deflate btrfs"
	else
	# 2.6
		if [ $KERNEL_VCODE -eq $(KernelVersionCode "2.6.37") ]; then
		    KERNEL_MODULES="${KERNEL_MODULES} hmac md4"
		fi
		if [ $KERNEL_VCODE -ge $(KernelVersionCode "2.6.32") ]; then
		    KERNEL_MODULES="${KERNEL_MODULES} hfsplus"
	    fi
	fi
else
	# 2.4
	KERNEL_MODULES="netlink_dev reiserfs scsi_mod sd_mod sg usbcore quota_v2"
	if [ "${ThisMachine}" = "ppc" ]; then
		KERNEL_MODULES="${KERNEL_MODULES} zlib_inflate"
	fi
	KERNEL_MODULES="${KERNEL_MODULES} fat vfat ntfs"
fi

if [ "$PLATFORM" = "evansport" ]; then
	VIDEO_MODULES="i2c-algo-bit button backlight thermal_sys video agpgart intel-gtt intel-agp fbdev drm fb output cfbimgblt cfbcopyarea cfbfillrect drm_kms_helper"
	KERNEL_MODULES="${KERNEL_MODULES} ${VIDEO_MODULES} udma"
fi

if [ "$PLATFORM" = "grantley" ]; then
	IPMI_MODULES="ipmi_msghandler ipmi_devintf ipmi_si"
	KERNEL_MODULES="${KERNEL_MODULES} ${IPMI_MODULES}"
fi

if [ "$PLATFORM" = "purley" ]; then
	IPMI_MODULES="ipmi_msghandler ipmi_devintf ipmi_si"
	KERNEL_MODULES="${KERNEL_MODULES} ${IPMI_MODULES}"
fi

SYNOLoadIPv6
SYNOLoadModules ${KERNEL_MODULES}
SYNOLoadAdt7490
SoftLink7490fanInput
SYNOLoadLED_lp3943

if [ $KERNEL_VCODE -ge $(KernelVersionCode "3.4") ]; then
	# Need to enable the two kernel config, CONFIG_DEVTMPFS and CONFIG_DEBUG_FS, CONFIG_SYNO_ENABLE_USBFS_ENTRY
	mount --bind /dev/bus/usb /proc/bus/usb
	mount -t debugfs none /sys/kernel/debug
	ln -s /sys/kernel/debug/usb/devices /proc/bus/usb/devices
else
	if [ $KERNEL_VCODE -ge $(KernelVersionCode "2.6") ]; then
		# usbfs need usbcore module
		RCMsg "Mounting usbfs" \
		mount -t usbfs /proc/bus/usb /proc/bus/usb
	else
		RCMsg "Mounting usbdevfs" \
		mount -t usbdevfs /proc/bus/usb /proc/bus/usb
	fi
fi

case "${ThisMachine}" in
armv5tel)
	NET_MODULES="sky2"
	;;
ppc)
	if [ $KERNEL_VCODE -ge $(KernelVersionCode "2.6") ]; then
		NET_MODULES="sk98lin skge"
	else
		NET_MODULES="sk98lin"
	fi
	;;
armv6l)
	NET_MODULES="mii gmac";
	;;
esac
if [ "$SUPPORT_DUAL_HEAD" = "yes" -a ! -f $FLAGE_FIND_MANUFACTORY_DEVICE ]; then
	/etc.defaults/AHAtasks load_network_modules_junior
fi
SYNOLoadModules ${NET_MODULES}


if [ "no" != "$RUN_SYNOBIOS" ]; then
	SYNOLoadModules "synobios"
	/bin/mknod /dev/synobios c 201 0 2>/dev/null
fi

# check Broadwell LAN status, must before synonetseqadj
if [ "yes" = "$SUPPORT_BDE_10G" ]; then
       /usr/syno/bin/synolanstatus
fi

# adjust NIC sequence
/usr/syno/bin/synonetseqadj

SYNOInitWireless "junior"

if [ -x /etc/rc.network ]; then
	CFGEN_NETWORK="/usr/syno/bin/synochecknetworkcfg"
	if [ -x "$CFGEN_NETWORK" ]; then
		$CFGEN_NETWORK
	fi
	/etc/rc.network start
	/etc/rc.network check-wifi-schedule
fi

syslogd_enable="YES"
syslogd_flags="-S"
case ${syslogd_enable} in
[Yy][Ee][Ss])
	# Transitional symlink (for the next couple of years :) until all
	# binaries have had a chance to move towards /var/run/log.
	if [ ! -L /dev/log ]; then
		# might complain for r/o root f/s
		ln -sf /var/run/log /dev/log
	fi

	rm -f /var/run/log
	RCMsg "Starting syslogd" \
	${syslogd_program:-/sbin/syslogd} ${syslogd_flags}
	/sbin/klogd
	;;
esac

echo "/root/@%e.core" >> /proc/sys/kernel/core_pattern
ulimit -c unlimited

# Reassemble the Pstore log into /var/log/pstore
/usr/syno/bin/syno_pstore_collect

/bin/grep eunitseq $SYNOINFO_DEF > /tmp/eunitseq

if [ -n "$MIN_FREE_KBYTES" ]; then
	echo $MIN_FREE_KBYTES >  /proc/sys/vm/min_free_kbytes
fi

StartServices()
{
	echo "Starting findhostd in flash_rd..."
	/usr/syno/bin/findhostd
	# network install mode only
	echo "Starting services in flash_rd..."
	for service_sh in /usr/syno/etc/rc.d/J*.sh; do
		if [ -x "$service_sh" ]; then
			echo "Running ${service_sh}..."
			"$service_sh" start
		fi
	done

	if [ "$PLATFORM" = "kvmx64" -o "$PLATFORM" = "nextkvmx64" ]; then
		echo "Starting guest daemons in flash_rd..."
		/usr/syno/bin/synoguestcommd
		/usr/syno/bin/synoguestcmdd
		# create second console channel
		if [ -e /dev/hvc0 ]; then
			/sbin/getty 115200 hvc0 &
		fi
	fi
}

is_mtest_bootloader_support()
{
	local ret=`cat /proc/cmdline | grep "MTEST_BOOTLOADER=1"`
	[ ! -z "$ret" ]
}

is_bootloader_mtest_tested()
{
	local ret=`/usr/syno/bin/mantool -get_mtest_ret | grep "Not tested"`
	[ -z "$ret" ]
}

RCMsg "Starting scemd"
if ! scemd ; then
	MsgWarn "Failed to start scemd. Reboot and get into steel plan or network install mode."
	touch "/.noroot"
	reboot
fi

if is_mtest_bootloader_support && is_bootloader_mtest_tested; then
	sh -c "echo 9 > /dev/ttyS1"
fi

if [ -x /etc/rc.network ]; then
	# Start PPPoE if enabled
	/etc/rc.network start-pppoe
fi

RCMsg "Starting services in background"
StartServices

#[DSM] #36950 - force to disable shortcut
if [ -f /proc/sys/kernel/syno_netfilter_status ]; then
	echo 1 > /proc/sys/kernel/syno_netfilter_status
fi

# For bug 1248, probe USB device after scemd
# usb-uhci.o is for VIA, usb-ohci.o is for NEC
# KERNEL_MODULES="ehci-hcd.o usb-uhci.o usb-storage.o printer.o"
if [ $KERNEL_VCODE -lt $(KernelVersionCode "2.6") ]; then
	KERNEL_MODULES="ehci-hcd usb-ohci usb-uhci usb-storage printer hid"
else
	KERNEL_MODULES="phy-stih407-usb phy-st-usb3 dwc3 dwc3-st hiusb-otg hiusb-ehci-hi3536 hiusb-xhci-hi3536 ehci-hcd ehci-pci ehci-platform ohci-hcd xhci-hcd etxhci-hcd st-hcd oxu210hp-hcd uhci-hcd usb-storage usblp input-core hid usbhid ehci-orion"
	if [ "$SUPPORT_DUAL_HEAD" = "yes" -a -f $FLAGE_FIND_MANUFACTORY_DEVICE ]; then
		KERNEL_MODULES="ehci-hcd ehci-pci ohci-hcd xhci-hcd etxhci-hcd oxu210hp-hcd uhci-hcd usblp input-core hid usbhid"
	fi
	SUPPORT_ACM=`/bin/get_key_value /etc.defaults/synoinfo.conf support_acm`
	if [ "$SUPPORT_ACM" == "yes" ]; then
		KERNEL_MODULES="${KERNEL_MODULES} cdc-acm"
		mknod /dev/ttyACM0 c 166 0
	fi
fi

SYNOLoadModules ${KERNEL_MODULES}

if [ "$SUPPORT_HDD_DYNAMIC_POWER" = "yes" ]; then
	SYNOLoadModules "syno_hddmon"
fi

# start burning test if no disk installed or has built-in storage
if should_burnin_test; then
	/usr/sbin/burnin_test -r &> /dev/null &
fi

# turn on no system led of built-in storage model
/usr/syno/bin/synohwctrl -set_stat_led nodisk

/usr/syno/sbin/manutild &

if [ -f /.memtest -a -x /usr/sbin/syno_memtester.sh ]; then
	swapoff $SwapDevice
	/usr/sbin/syno_memtester.sh &
fi

# create ubi_ctrl device if exist
if [ -e /sys/devices/virtual/misc/ubi_ctrl ]; then
	MAJOR=`cat /sys/devices/virtual/misc/ubi_ctrl/dev | cut -d':' -f 1`;
	MINOR=`cat /sys/devices/virtual/misc/ubi_ctrl/dev | cut -d':' -f 2`;
	mknod /dev/ubi_ctrl c $MAJOR $MINOR;
fi

if [ "$SUPPORT_DUAL_HEAD" = "yes" -a ! -f $FLAGE_FIND_MANUFACTORY_DEVICE ]; then
	/etc.defaults/AHAtasks junior_stage
	/etc.defaults/AHAtasks junior_monitor_reboot_or_poweroff &
fi

if [ "xyes" == "x$SUPPORT_LOCALINSTALL" -a -f "/etc/nvrlicheck.sh" ]; then
    #Additional check for the need of producting tool
    cat /proc/cmdline | grep -i "no_localinstall" > /dev/null 2>&1
    if [ 0 -ne $? ]; then
        /etc/nvrlicheck.sh &
    fi
fi

echo "============ Date ============"
date
echo "=============================="

exit 0
