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

# Set pin mux for HI3535
if [ "hi3535" == `/bin/get_key_value /etc.defaults/synoinfo.conf unique | cut -d"_" -f2` ]; then
	echo "[SYNO] set pin mux for hi3535 " > /dev/kmsg
	. /etc.defaults/rc.clkcfg_hi3535 > /dev/null || echo "[SYNO] fail to run rc.clkcfg_hi3535" > /dev/kmsg
	. /etc.defaults/rc.sysctl_hi3535 > /dev/null || echo "[SYNO] fail to run rc.sysctl_hi3535" > /dev/kmsg
	. /etc.defaults/rc.pinctrl_hi3535_aic31 > /dev/null || echo "[SYNO] fail to run rc.pinctrl_hi3535_aic31" > /dev/kmsg
fi

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

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

SYNOCheckAndUnloadModules "ehci-hcd"

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`
IPv4_ONLY=`get_key_value $SYNOINFO_DEF ipv4only`

SUPPORT_DUAL_HEAD=`/bin/get_key_value /etc.defaults/synoinfo.conf support_dual_head`
SUPPORT_HA=`get_key_value $SYNOINFO_DEF support_ha`
SUPPORT_RAID=`get_key_value $SYNOINFO_DEF supportraid`
SUPPORT_SYNOACL=`get_key_value $SYNOINFO_DEF support_synoacl`
SUPPORT_STARTUPD=`get_key_value $SYNOINFO_DEF supportstartupd`
SUPPORT_HDD_HOTPLUG=`get_key_value $SYNOINFO_DEF HddHotplug`
SUPPORT_ZRAM=`get_key_value $SYNOINFO_DEF support_zram`
SUPPORT_ENC_POWERCTL=`get_key_value $SYNOINFO_DEF support_enc_powerctrl_onoff`
SUPPORT_LED_BRIGHTNESS_ADJUSTMENT=`get_key_value $SYNOINFO_DEF support_led_brightness_adjustment`

SZF_HA_RC="/usr/syno/synoha/etc.defaults/rc.ha"
SZF_DUAL_RC="/usr/syno/synodual/etc/rc.dual"
SupportSAS=`/bin/get_key_value /etc.defaults/synoinfo.conf supportsas`

UsbStation=`/bin/get_key_value /etc.defaults/synoinfo.conf usbstation`
SUPPORT_POWER_OFF=`get_key_value $SYNOINFO_DEF support_poweroff`
MMCBLK0="/sys/block/mmcblk0"
SUPPORT_MMC_BOOT=`get_key_value $SYNOINFO_DEF support_emmc_boot`
ThermalModule="thermal_ctrl"
SUPPORT_AESNI_INTEL=`get_key_value $SYNOINFO_DEF support_aesni_intel`

# disk topology required kernel modules on SAS model, for #44960
SG_MODULES="sg"

RCMsg "Starting /etc/rc"

if [ -f /var/.UpgradeBootup ]; then
	/usr/bin/python -m compileall
	/usr/bin/python -O -m compileall
fi

/usr/syno/bin/synobootseq --set-start-etcrc >/dev/null 2>&1

# do cfgen to correct config
for CFGEN in /usr/syno/cfgen/*;
do
	## s00_synocheckfstab need run after spacetool
	if [ "$CFGEN" == "/usr/syno/cfgen/s00_synocheckfstab" ]; then
		continue;
	fi
	if [ -x "$CFGEN" ]; then
		$CFGEN
	fi
done
ENABLE_ZRAM=`get_key_value $SYNOINFO enable_zram`
RUN_HA=`get_key_value $SYNOINFO runha`
RUN_SYNOBIOS=`get_key_value $SYNOINFO synobios`

# Dump platform information to /.system_info/
/usr/syno/bin/synoplatform --dump-info

rm -rf /var/state/ups/*
# synobootseq write boot state in tmp directory
/usr/syno/bin/synobootseq --set-start-etcrc >/dev/null 2>&1

[ -f /initrd/tmp/usbinfoall ] && cp -f /initrd/tmp/usbinfoall /tmp/usbinfoall
[ -d /initrd ] && [ ! -f /.nofree ] && /bin/umount /initrd && /sbin/freeramdisk /dev/ram0

# reset usbdev.conf before handle usb device hotplug
rm -f /usr/syno/etc/usbdev.conf

# reset network bridge setting, to prevent wifi plug-out when poweroff
/etc/rc.network reset-wireless-config >/dev/null 2>&1

# the order should be migrate => correct runkey => clean custom => HA => correct override => runlevel 1
if [ -f "/var/.UpgradeBootup" ]; then
	/usr/syno/sbin/synoservicemigrate --all
fi
/usr/syno/sbin/synoservicecfg --correct-runkey
/usr/syno/sbin/synoservicecfg --clean-custom
if [ "yes" == "$RUN_HA" ]; then
	/usr/syno/sbin/synoservicecfg --pause-all-no-action ha-passive ha-on-passive
	# passive should run hotplugd, but pause here till the role is decided(in rc.ha)
	/usr/syno/sbin/synoservicecfg --pause-by-reason hotplugd ha-passive
	# ha not support services
	# Don't forget SxxPre.sh
	/usr/syno/sbin/synoservicecfg --pause-by-reason synowifid ha-not-support
	/usr/syno/sbin/synoservicecfg --pause-by-reason bluetoothd ha-not-support
	/usr/syno/sbin/synoservicecfg --pause-by-reason btacd ha-not-support
fi
/usr/syno/sbin/synoservicecfg --correct-override

# start udev to handle hotplug event,
# udev need start before mindspeed pfe_insert
# to avoid mindspeed load firmware timeout
/sbin/initctl start udevd &

# Mindspeed's platform needs further settings and pfe module insertion
if [ "x" != "x`/bin/get_key_value /etc.defaults/synoinfo.conf unique | grep comcerto2k`" ]; then
	. /etc.defaults/rc.mindspeed pfe_insert
fi

create_mmc_dev()
{
	# remove to-be faked device: sdaX / hdaX
	/bin/rm -f /dev/sda
	/bin/rm -f /dev/hda
	for i in $(seq 15); do
		/bin/rm -f /dev/sda${i};
		/bin/rm -f /dev/hda${i};
	done

	# wait device probe done */
	local _count=0;
	while [ ! -e ${MMCBLK0} ]; do
		# wait most 10 seconds
		if [ $_count -ge 10 ]; then
			echo "eMMC device failed.";
			return 1;
		fi

		echo "wait 1 second for eMMC device ready..."
		sleep 1;
		_count=$((_count + 1))
	done

	# creat faked sdaX / hdaX, also mmcblk0
	source ${MMCBLK0}/uevent;
	/bin/mknod /dev/sda b ${MAJOR} ${MINOR}
	/bin/mknod /dev/hda b ${MAJOR} ${MINOR}
	/bin/mknod /dev/mmcblk0 b ${MAJOR} ${MINOR}
	for i in $(seq 4); do
		/bin/mknod /dev/sda${i} b ${MAJOR} $((MINOR + i))
		/bin/mknod /dev/hda${i} b ${MAJOR} $((MINOR + i))
		/bin/mknod /dev/mmcblk0p${i} b ${MAJOR} $((MINOR + i))
	done
}

CheckErasingNode()
{
	EraseList=`/bin/ls /dev/erase*`
	if [ -n "$EraseList" ]; then
		for EraseNode in $EraseList; do
			SDNode=`echo $EraseNode | sed 's/erase//g'`
			/bin/mv $EraseNode $SDNode
		done
	fi
}

CreateFackedDevHda()
{
	/bin/mknod /dev/hda b 8 0
	/bin/mknod /dev/hda1 b 8 1
	/bin/mknod /dev/hda2 b 8 2
	/bin/mknod /dev/hda3 b 8 3
	/bin/mknod /dev/hda4 b 8 4
}

# For B#66473, after enable devtmpfs, /dev/hda* do not exist anymore.
# However, the old updater on 1-bay model will check if hda exist.
# This change cause 1-bay downgrade failed due to hda missing.
# For downgrade compatibility, we add facked hda back
# Exclude EDS14.
if [ "${SUPPORT_MMC_BOOT}" != "yes" ]; then
	CreateFackedDevHda
fi

if [ "$SupportSAS" = "yes" ]; then
	. /etc.defaults/rc.sas
	SASRemoveSDNode
	SASEnablePhy
# Only EDS14 can do "create_mmc_dev".
elif [ "${SUPPORT_MMC_BOOT}" == "yes" ]; then
	create_mmc_dev
else
	CheckErasingNode
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

	local ipv6mods="ipv6"
	# load IPv6-in-IPv4 module
	if [ $KERNEL_VCODE -ge $(KernelVersionCode "3.10") ]; then
		ipv6mods="$ipv6mods ip_tunnel"
	fi
	ipv6mods="$ipv6mods tunnel4 sit"

	SYNOLoadModules $ipv6mods
}

UpgradeConfig()
{
	Event=$1

	if [ ! -f "/var/.UpgradeBootup" ]; then
		return;
	fi

	orgVer="/.old_patch_info/VERSION"
	if [ -f "/.updater" ]; then
		upgType="migrate"
	else
		upgType="upgrade"
	fi

	if [ -f $orgVer ]; then
		/usr/syno/bin/configupdate -c $Event -t $upgType -p $orgVer
	else
		echo "Skip update config because not found ${orgVer}"
	fi
}

SYNOLoadIPMIModule()
{
	local support_ipmi=`get_key_value $SYNOINFO_DEF support_ipmi`
	if [ "$support_ipmi" = "yes" ]; then
		SYNOLoadModules ipmi_msghandler ipmi_devintf ipmi_si
	fi
}

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

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

# see if need repartitioning
/etc/newdisk.sh

SYNOLoadModules ${SG_MODULES}
# we need sg.ko before we can assign enclosure id
if [ "$SupportSAS" = "yes" -a -d /initrd ]; then
	. /etc.defaults/rc.sas
	SASAssignEncID
	SASTunDiskPerformance & # let another thread to run this script
	SASInterruptDiskSelfTest & # when powering on, there is possible disk self test running, stop it for #47006
fi
# turn swap on
if [ "yes" != "${UsbStation}" ]; then
	if [ "$SUPPORT_RAID" != "yes" ]; then
		SwapDevice="/dev/sda2"
	else
		SwapDevice="/dev/md1"
		#dualhead model will assemble /dev/md1 on linuxrc.syno.
		if [ "yes" != "${SUPPORT_DUAL_HEAD}" ]; then
			# For legacy compatible
			grep -q md9999 /proc/mdstat && mdadm -S /dev/md9999

			/usr/syno/bin/synocheckswapconfig
			CheckSwapRaid
			if [ $? -ne 0 ]; then
				swapoff $SwapDevice
				mdadm -S $SwapDevice
				MkSwapRaid 1
			fi
		fi
	fi

	mkswap $SwapDevice
	swapon $SwapDevice

	if [ $? -ne 0 -a -d /initrd ]; then
		logger -s -t rc -p err "Failed to swapon ${SwapDevice}, reboot to network install mode."
		touch "/.noroot"
		reboot
	fi

	if test "$SUPPORT_ZRAM" = "yes" -a "$ENABLE_ZRAM" = "yes" ; then
		/usr/syno/bin/synozram start
	fi

fi

/usr/syno/bin/synobootseq --set-start-services >/dev/null 2>&1
/sbin/telinit 1

ConfList="/etc/sysconfig/network"
for ThisConfig in $ConfList;
do
	if [ -r "$ThisConfig" ]; then
		. $ThisConfig
	fi
done

ThisMachine=`uname -m`
if [ $KERNEL_VCODE -ge $(KernelVersionCode "2.6") ]; then
	# 2.6 or 3.x
	MLX_MODULES="compat mlx_compat mlx4_core mlx4_en"
	I40E_MODULES="configfs i40e"
	NET_DRIVERS="dca e1000e i2c-algo-bit igb be2net ixgbe ${I40E_MODULES} tn40xx ${MLX_MODULES}"
	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 m86xxx_elp aes-x86_64 aes-i586 ecb sha1_generic sha256_generic sha512_generic ecryptfs cryptosoft cryptd arc4"
	AESNI_MODULES="ablk_helper gf128mul lrw glue_helper aesni-intel"
	if [ "$SUPPORT_AESNI_INTEL" == "yes" ]; then
		CRYPTO_MODULES="${CRYPTO_MODULES} ${AESNI_MODULES}"
	fi
	if [ -f /lib/modules/crc32c-intel.ko ]; then
		CRYPTO_MODULES="${CRYPTO_MODULES} crc32c-intel"
	fi
	RAID_MODULES="dm-mod async_tx async_memcpy xor async_xor raid6_pq async_pq async_raid6_recov linear raid0 raid10 raid456"
	KERNEL_MODULES="llc p8022 psnap 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"
	KERNEL_I2C_MODLES="i2c-core of_i2c i2c-mpc"
	if [ "ppc853x" = "$PLATFORM" ]; then
		KERNEL_MODULES="${RAID_MODULES} ${KERNEL_MODULES} ${CRYPTO_MODULES} ${KERNEL_I2C_MODLES}"
	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"
	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 [ "$SUPPORT_SYNOACL" = "yes" ]; then
	KERNEL_MODULES="${KERNEL_MODULES} synoacl_vfs"
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" = "braswell" ]; then
	VIDEO_MODULES="i2c-algo-bit button backlight thermal_sys video agpgart intel-gtt intel-agp fbdev fb drm output cfbimgblt cfbcopyarea cfbfillrect drm_kms_helper i915"
	KERNEL_MODULES="${KERNEL_MODULES} ${VIDEO_MODULES}"
fi

if [ -f /lib/modules/zfs.ko ]; then
	KERNEL_MODULES="${KERNEL_MODULES} spl znvpair zcommon zavl zunicode zfs"
fi

if [ -f /lib/modules/btrfs.ko ]; then
	KERNEL_MODULES="${KERNEL_MODULES} btrfs"
fi

SYNOLoadIPv6
SYNOLoadModules ${KERNEL_MODULES}
SYNOLoadAdt7490
SoftLink7490fanInput
SYNOLoadLED_lp3943
SYNOLoadIPMIModule

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
SYNOLoadModules ${NET_MODULES}

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


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

SYNOInitWireless
/sbin/initctl emit network-starting NETWORKING=${NETWORKING}

if [ -r "/etc.defaults/sysctl.conf" ]; then
	/sbin/sysctl -p /etc.defaults/sysctl.conf
fi

#This should be done after configuration upgrade and before spacetool
/bin/grep eunitseq $SYNOINFO_DEF > /tmp/eunitseq
if [ "$SUPPORT_ENC_POWERCTL" = "yes" -a "$SUPPORT_DUAL_HEAD" != "yes" ]; then
	# dualhead wait enclosure HDD in AHAtasks
	. /etc.defaults/rc.sas
	SASWaitEncHDDReady
fi

/sbin/start grinst-create-vol

#Start space
if [ -x /usr/syno/bin/spacetool.shared ]; then
	/usr/syno/bin/spacetool.shared --bootup-assemble
	if [ "yes" != "$RUN_HA" ]; then
		/usr/syno/bin/synovspace -all-load
	fi
	#adjust default sync speed to 10 MB/s as minimum
	/sbin/sysctl -w dev.raid.speed_limit_min=10000
	/usr/syno/cfgen/s00_synocheckfstab
fi


LOCALE_CHECKER="/usr/syno/locale/locale_checker.sh"
if [ ! -x "$LOCALE_CHECKER" ]; then
	chmod 755 $LOCALE_CHECKER
fi
$LOCALE_CHECKER

# get original value for setting below.
GRINST_OK="/.GRINST_OK"
WEBINST_OK="/.WEBINST_OK"
if [ -f ${GRINST_OK} -o -f ${WEBINST_OK} ]; then
	echo "Group/Web Installation OK, auto set configured."
	grep -v "^configured=" /etc/synoinfo.conf > /tmp/synoinfo.conf
	echo "configured=\"yes\"" >> /tmp/synoinfo.conf
	mv /tmp/synoinfo.conf /etc/synoinfo.conf
	if [ -f ${GRINST_OK} ]; then
		/usr/syno/bin/synosetkeyvalue ${SYNOINFO} install_agent groupinstall
	elif [ -f ${WEBINST_OK} ]; then
		/usr/syno/bin/synosetkeyvalue ${SYNOINFO} install_agent webinstall
	fi
	if [ ! -f /.ds_configure_post_vol.sh ]; then
		rm -f ${GRINST_OK}
		rm -f ${WEBINST_OK}
	fi
	if [ -f /.ds_configure.sh ]; then
		/.ds_configure.sh
	fi
fi
rm -f /.ds_configure.sh > /dev/null 2>&1
if [ -f /.ASTINST_OK ]; then
	/usr/syno/bin/synosetkeyvalue ${SYNOINFO} install_agent dsassistant
	rm -f /.ASTINST_OK
fi

if [ "yes" = "$RUN_HA" ]; then
	$SZF_HA_RC prepare-for-upg
	UpgradeConfig "volume_ready"
else
	# checking and Mounting filesystem(s) ...
	/usr/syno/bin/synobootseq --set-check-fs  >/dev/null 2>&1
	/etc.defaults/rc.volume start
	# reset bootseq to start-services
	/usr/syno/bin/synobootseq --set-start-services >/dev/null 2>&1
	#Upgrade configuration files
	UpgradeConfig "volume_ready"
	/sbin/initctl emit --no-wait syno.volume.ready
fi

# check if shutdown normally
if [ -f "/var/.NormalShutdown" ]; then
	rm -f "/var/.NormalShutdown"
elif [ -f "/.NormalShutdown" ]; then
	rm -f "/.NormalShutdown"
elif [ "yes" == "${SUPPORT_POWER_OFF}" ]; then
	# to notice user in S99zbookok.sh
	touch "/tmp/.ImproperShutdown"
fi

#set time zone information to kernel
/usr/syno/bin/synokerneltz

/sbin/sysctl -w kernel.core_pattern=/volume1/@%e.core

if [ $KERNEL_VCODE -ge $(KernelVersionCode "2.6") ]; then
	/sbin/sysctl -w fs.suid_dumpable=2
else
	/sbin/sysctl -w kernel.suid_dumpable=2
fi
ulimit -c unlimited

if /bin/uname -a | /bin/egrep "(x86|i686)" > /dev/null 2>&1 ; then
	# i686 is for evansport (x86 32bit)
	/sbin/sysctl -w vm.min_free_kbytes=65536
elif [ 1048576 -le "`awk '"MemTotal:"==$1{print $2}' /proc/meminfo`" ]; then
	# if physical memory size greater than 1GB, and then set vm.min_free_kbytes to 64MB
	/sbin/sysctl -w vm.min_free_kbytes=65536
elif [ $KERNEL_VCODE -ge $(KernelVersionCode "2.6.32") ]; then
	/sbin/sysctl -w vm.min_free_kbytes=8192
else
	/sbin/sysctl -w vm.min_free_kbytes=4096
fi

if [ "$PLATFORM" = "armada370" ]; then
	/sbin/sysctl -w net.ipv4.tcp_rmem="4096 87380 913920"
fi

# enlarge ARP cache size
/sbin/sysctl -w net.ipv4.neigh.default.gc_thresh1=256
/sbin/sysctl -w net.ipv4.neigh.default.gc_thresh2=1024
/sbin/sysctl -w net.ipv4.neigh.default.gc_thresh3=2048

# enlarge this quota so that we can mount more encyption share simultaneously
/sbin/sysctl -w kernel.keys.root_maxbytes=200000

if [ -f ${GRINST_OK} -o -f ${WEBINST_OK} ]; then
	if [ -f /.ds_configure_post_vol.sh ]; then
		/.ds_configure_post_vol.sh
	fi
	rm -f ${GRINST_OK}
	rm -f ${WEBINST_OK}
fi
rm -f /.ds_configure_post_vol.sh > /dev/null 2>&1

# System log: "System started to boot up."
/usr/syno/bin/synologset1 sys info 0x11100002

/usr/syno/etc/rc.ssl_keygen > /dev/null 2>&1 &

if [ "yes" = "$SUPPORT_HA" ]; then
	$SZF_HA_RC ha-pkg-check
fi

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 [ "yes" = "$SUPPORT_HA" ] && [ "yes" = "$RUN_HA" ]; then
	$SZF_HA_RC start
else
	RCMsg "Starting services in background"
	/sbin/start dsm-services &
fi

/sbin/start network-pppoe NETWORKING=${NETWORKING}

# 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"
elif [ $KERNEL_VCODE -ge $(KernelVersionCode "3.6") ]; then
	# Add hid-generic.ko into module list for new kernel (>= 3.6).
	# CONFIG_HID_GENERIC should be enabled
	KERNEL_MODULES="phy-stih407-usb phy-st-usb3 dwc3 dwc3-st ehci-hcd ehci-pci ehci-platform ohci-hcd xhci-hcd etxhci-hcd st-hcd oxu210hp-hcd uhci-hcd usb-storage ehci-orion"
	if [ "$SUPPORT_DUAL_HEAD" != "yes" ]; then
		KERNEL_MODULES="${KERNEL_MODULES} usblp input-core hid usbhid hid-generic"
	fi
else
	KERNEL_MODULES="ehci-hcd ehci-pci ohci-hcd xhci-hcd etxhci-hcd oxu210hp-hcd uhci-hcd usb-storage"
	if [ "$SUPPORT_DUAL_HEAD" != "yes" ]; then
		KERNEL_MODULES="${KERNEL_MODULES} usblp input-core hid usbhid"
	fi
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

SYNOLoadModules ${KERNEL_MODULES}

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

## check if rc.local contain malware pattern
if [ -f /etc/rc.local ]; then
	if grep -E "/var/run|synoman" /etc/rc.local; then
		mv /etc/rc.local /etc/rc.local.bak
		touch /.malware_detect_67278
	fi
fi

## Notify user when rc.local contain detect
## malware pattern "/var/run" and "synoman"
## See B#67278 for more information
if [ -f /.malware_detect_67278 ]; then
	/usr/syno/bin/synodsmnotify @administrators dsmnotify:system_event "Customized start-up script rc.local has been rename to rc.local.bak due to contain malware pattern. Please contact Synology support if you have any concern."
	/usr/syno/bin/synologset1 sys warn 0x11100018
	rm /.malware_detect_67278
fi

if [ -r /etc/rc.local ]; then
	echo -n 'Starting local daemons:'
	cat /etc/rc.local
	sh /etc/rc.local
fi

# Adjust share memory max number for the max camera support number of Surveillance Station
if [ "$PLATFORM" = "bromolow" -o "$PLATFORM" = "grantley" -o "$PLATFORM" = "broadwell" ]; then
	SHMMNI=`cat /proc/sys/kernel/shmmni`
	SHMMNI_TARGET=16384
	if [ ${SHMMNI_TARGET} -gt ${SHMMNI} ]; then
		/sbin/sysctl -w kernel.shmmni=${SHMMNI_TARGET}
	fi
fi

# Adjust max semphore array size for the max camera support number of Surveillance Station
SEM_ARRAY_SIZE=`cat /proc/sys/kernel/sem | awk '{print $4}'`
SEM_TARGET=${SEM_ARRAY_SIZE}
case "${PLATFORM}" in
bromolow|grantley|bromolowESM|broadwell)
	SEM_TARGET=1024
	;;
alpine|alpine4k|armadaxp|avoton|cedarview|evansport|braswell)
	SEM_TARGET=512
	;;
esac

if [ "${PLATFORM}" = "monaco" ]; then
	sleep 5;
	/usr/syno/etc.defaults/MonacoSDKInstall.sh
fi

if [ ${SEM_TARGET} -gt ${SEM_ARRAY_SIZE} ]; then
	/sbin/sysctl -w kernel.sem="`cat /proc/sys/kernel/sem | awk '{print $1 " " $2 " " $3}'` ${SEM_TARGET}"
fi

/usr/syno/sbin/manutild &

if [ -f /usr/syno/bin/syno_hdd_util ]; then
	syno_hdd_util --ssd_detect --without-id-log 2>/dev/null
fi

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

if [ "$SUPPORT_DUAL_HEAD" = "yes" ]; then
	/usr/syno/synoaha/bin/synoaha --init-mgr-daemon-version
	/usr/syno/synoaha/bin/syno_aha_mgr_daemon active_stage &
	/usr/syno/synoaha/bin/synoahamonmd0_static &
fi

if [ "${SUPPORT_LED_BRIGHTNESS_ADJUSTMENT}" == "yes" ]; then
	mkdir /tmp/syno_led_brightness
	cp /usr/syno/bin/syno_led_brightness /tmp/syno_led_brightness/syno_led_brightness
	cp /usr/syno/etc/led_brightness.xml /tmp/syno_led_brightness/led_brightness.xml
	# update LED brightness
	/tmp/syno_led_brightness/syno_led_brightness --update --force
fi

exit 0
