#!/bin/ash
# Kiran Kamity, 05/11/2004
# Sreen Tallam, 04/04/2008
# Sreen Tallam, 08/08/2008
# Any Netapp additions to the initial sequence of events that must run on
# the RLM go in this file
#set -x

plat=$(cat /proc/platform)

# Copied from module-init-tools for early load of gpio driver
if [ -w /lib/modules/$KVER/ ]; then
  if [ -x /sbin/depmod  ]
  then
    echo -n "Calculating module dependencies... "
    depmod -n > /var/modules.dep
    ln -sf /var/modules.dep /lib/modules/$KVER/modules.dep
    echo "done."
  fi
else
  echo "Not running depmod because /lib/modules/$KVER/ is not writeable."
fi

# This string "str_platformID" is passed to GPIO driver for platform detection(ie) module_param(str_platformID, charp,0000)
modprobe gpio str_platformID=$plat || true

case "$1" in

	start|"")

		# Unmounting the old root if it exists
		# This saves us a lot of RAM (about 9 MB)
		if [ -d /oldroot ]
		then
			umount /oldroot
			rmdir /oldroot
		fi

		# Create a new tempfs for syslog so it won't affect other if the log is getting too big
		# before rotation

		mount -t tmpfs syslog /var/log -o size=4M
		
		#
		# Create this empty syslog file for logroatation to work
		touch /etc/init.d/syslog
		chmod 755 /etc/init.d/syslog 

		# Create these files that are not created in 2.6.18
		mkdir -p /dev/root
		mkdir -p /var/lock
		
		# Create two more directories for sshd purposes
		mkdir -p /var/empty
		mkdir -p /var/empty/sshd

		# Create dirs necessary for cron and logrotate
		mkdir -p /var/lib/logrotate;
		mkdir -p /var/spool;

		# Fix device permission
		chmod 666 /dev/null
		chmod 666 /dev/zero
		chmod 666 /dev/random
		chmod 666 /dev/i2c-0
		chmod 666 /dev/i2c-1
		chmod 666 /dev/i2c-2
		chmod 666 /dev/i2c-3
		chmod 666 /dev/i2c-4
		chmod 666 /dev/i2c-5
		chmod 666 /dev/i2c-6
		chmod 666 /dev/i2c-7
		chmod 666 /dev/i2c0
		chmod 666 /dev/i2c1
		chmod 666 /dev/i2c2
		chmod 666 /dev/i2c3
		chmod 666 /dev/i2c4
		chmod 666 /dev/i2c5
		chmod 666 /dev/i2c6
		chmod 666 /dev/i2c7
		chmod 666 /dev/mtd2
		chmod 666 /dev/mtd5
		chmod 666 /dev/gpio0
		chmod 666 /dev/jtag0
		chmod 666 /dev/pwmtach
		chmod 666 /dev/spim
		chmod 666 /dev/pos
		chmod 666 /dev/mdcio0
		chmod 666 /dev/mdcio1
		if [ -f /dev/tty ] ; then
			chmod 666 /dev/tty
		fi

		# Figure out whether we are booted from primary or backup images
		rm -f /var/run/backup_fw

		current_boot_image=`/usr/local/bin/fw_printenv | grep image= | sed 's/image=//g'`;

		# If last bit of tiny ROM is 0, then our NAND is flipped (primary is the bottom half)
		hexdump /dev/mtd0 | grep "ffff ffff ffff ffff ffff ffff ffff fffe" > /dev/null
		not_bottom=$?

		echo "Booting from" $current_boot_image

		echo "Mounting primary and backup read-only"
		# Mount jffs2_rootfs primary and backup as read-only
		if [ $not_bottom -eq 0 ] ; then
			echo "Primary partition is bottom"
			mount -o ro -t jffs2 /dev/mtdblock9 /mnt/jffs2_rootfs_primary;
			mount -o ro -t jffs2 /dev/mtdblock7 /mnt/jffs2_rootfs_backup;
		else
			echo "Primary partition is top"
			mount -o ro -t jffs2 /dev/mtdblock7 /mnt/jffs2_rootfs_primary;
			mount -o ro -t jffs2 /dev/mtdblock9 /mnt/jffs2_rootfs_backup;
		fi

		mount -t jffs2 /dev/mtdblock11 /mnt/sapps;

		mount -t jffs2 /dev/mtdblock10 /mnt/logs;
		if [ $? -ne 0 ] ; then
			#Erase and Rewrite the partition
			/usr/bin/mkfs.jffs2  --root=/etc/defconfig  --output=/install/Config.bin
			/usr/local/bin/clrlog.sh

			#Mount the partition again
			mount -t jffs2 /dev/mtdblock10 /mnt/logs;
			/usr/local/bin/sel_logger "SP.notice" "Erased log partition to resolve mount issues"
		fi

		# Create directories to download programmable devices fw to upgrade using default_fw_program.sh
		mkdir -p /firmware/RazorL/battery
		mkdir -p /firmware/RazorL/ddr
		mkdir -p /firmware/RazorL/fan
		mkdir -p /firmware/RazorL/fpga
		mkdir -p /firmware/RazorL/pcieswitch

		mkdir -p /firmware/RazorM/battery
		mkdir -p /firmware/RazorM/ddr
		mkdir -p /firmware/RazorM/ebod
		mkdir -p /firmware/RazorM/fpga
		mkdir -p /firmware/RazorM/pcieswitch

		if [ "$current_boot_image" == "secondary" ] ; then
			touch /var/run/backup_fw;
			ln -s /mnt/jffs2_rootfs_backup/firmware/RazorL/switch /firmware/RazorL/switch
			ln -s /mnt/jffs2_rootfs_backup/firmware/RazorM/switch /firmware/RazorM/switch
			# Does backup log partition need to be cleared ?
			if [ -d /mnt/logs/install/backup/defconfig ] ; then
				#This essentially removes the Config.bin out of the rootfs
				#It's better to copy mem-flash than flash-flash
				echo "Found default configuration for wipeclean of backup file system"
				mv /mnt/logs/install/backup/defconfig/ /install/
				/usr/local/bin/clrlog.sh
			fi
		else
			ln -s /mnt/jffs2_rootfs_primary/firmware/RazorL/switch /firmware/RazorL/switch
			ln -s /mnt/jffs2_rootfs_primary/firmware/RazorM/switch /firmware/RazorM/switch
			# Does primary log partition need to be cleared ?
			if [ -d /mnt/logs/install/primary/defconfig ] ; then
				#This essentially removes the Config.bin out of the rootfs
				#It's better to copy mem-flash than flash-flash
				echo "Found default configuration for wipeclean of primary file system"
				mv /mnt/logs/install/primary/defconfig/ /install/
				/usr/local/bin/clrlog.sh
			fi
		fi

		# Handle the case when log partition is empty
		if ! [ -d /mnt/logs/etc/ssh ] ; then
			mkdir -p /mnt/logs/etc/ssh;
		fi

		# The eth1 port is now used for NC-SI and should not be disabled
		#eth1=`grep -c "auto eth1" /mnt/logs/etc/network/interfaces`;
		#if [ $eth1 -eq 1 ] ; then
			#echo "Disable eth1"
			#rm -f /mnt/logs/etc/network/interfaces;
			#cp /etc/defconfig/etc/network/interfaces /mnt/logs/etc/network/.
		#fi

		if [ -f /proc/sys/net/ipv6/conf/default/accept_dad ]; then
			echo 1 > /proc/sys/net/ipv6/conf/default/accept_dad;
		fi
		if [ -f /proc/sys/net/ipv6/conf/all/accept_dad ]; then
			echo 1 > /proc/sys/net/ipv6/conf/all/accept_dad;
		fi
		if [ -f /proc/sys/net/ipv6/conf/eth0/accept_dad ]; then
			echo 1 > /proc/sys/net/ipv6/conf/eth0/accept_dad;
		fi

		if [ -f /proc/sys/net/ipv6/conf/default/accept_ra_rt_info_max_plen ]; then
			echo 64 > /proc/sys/net/ipv6/conf/default/accept_ra_rt_info_max_plen;
		fi
		if [ -f /proc/sys/net/ipv6/conf/all/accept_ra_rt_info_max_plen ]; then
			echo 64 > /proc/sys/net/ipv6/conf/all/accept_ra_rt_info_max_plen;
		fi
		if [ -f /proc/sys/net/ipv6/conf/eth0/accept_ra_rt_info_max_plen ]; then
			echo 64 > /proc/sys/net/ipv6/conf/eth0/accept_ra_rt_info_max_plen;
		fi

        #
        # configure the router address acceptance in eth0 now, before the adapter is brought up
        # in later scripts.  If not set, the adapter automagically gets an router assigned address when starting
        # a match with grep will produce $? of 0, which is what we want because the
        # the flag to set in linux is the inverse of the flag sent by the loader
        #
        grep "ra_disable.*1" < /mnt/logs/etc/rlm_config_from_filer
        accept_ra=$?
        echo ${accept_ra}  > /proc/sys/net/ipv6/conf/eth0/accept_ra

        revid_0=$(/usr/local/bin/gpiotool --get-data 3 12 | grep -c "Pin is High")
        revid_1=$(/usr/local/bin/gpiotool --get-data 3 13 | grep -c "Pin is High")
        revid_2=$(/usr/local/bin/gpiotool --get-data 3 14 | grep -c "Pin is High")
        revid_3=$(/usr/local/bin/gpiotool --get-data 3 15 | grep -c "Pin is High")
        brdrev=$( expr $revid_3 \* 8 + $revid_2 \* 4 + $revid_1 \* 2 + $revid_0)
		razorl_rev_p2i=3

		mkdir -p /mnt/logs/etc/network;
		if ! [ -s /mnt/logs/etc/network/interfaces ] ; then
            #if not RazorL pre-p2i, default to ATT/Vespa vlan config
            #(THIS WILL NOT WORK USING OTHER U-BOOTs SINCE IT RELIES ON fw_printenv)
            if [ $plat == "RazorL" ] && [ $brdrev -lt $razorl_rev_p2i ] ; then
                cp /etc/defconfig/etc/network/interfaces.RazorNIC /mnt/logs/etc/network/interfaces
            else
			    cp /etc/defconfig/etc/network/interfaces.RazorSW /mnt/logs/etc/network/interfaces
            fi
		fi

		if ! [ -d /mnt/logs/ipmi ] ; then
			mkdir -p /mnt/logs/ipmi;
		fi

		if ! [ -d /mnt/logs/ipmi/errlog ] ; then
			mkdir -p /mnt/logs/ipmi/errlog;
		fi
		
		if ! [ -f /mnt/logs/messages ] ; then
			touch /mnt/logs/messages
		fi
		ln -s /mnt/logs/messages /var/log/messages
		
		if [ -e /mnt/logs/messages.1 ] ; then
		    ln -s /mnt/logs/messages.1 /var/log/messages.1
		fi

		if ! [ -d /mnt/logs/var ] ; then
			mkdir -p /mnt/logs/var;
		fi

		if [ -f "/mnt/logs/var/RLM_debugmode" ] ; then
			rm /mnt/logs/var/RLM_debugmode
		fi

		# Creating links to primary and backup metadata info
		mkdir -p /etc/rlm_install;

		ln -sf /mnt/jffs2_rootfs_primary/install /etc/rlm_install/primary;
		ln -sf /mnt/jffs2_rootfs_backup/install /etc/rlm_install/backup;

		# Start syslogd-ipv6
		#syslogd-ipv6 -m 0;

		# Start klogd
#		/sbin/klogd

		#fix the RLM interface file since RLM SW expect it in a diffent place
		#
		ln -sf ./network/interfaces /mnt/logs/etc/interfaces

		# If the passwdFlag is present, it means that we got rebooted in the midst of updating the 
		# logs partition. In that case, we just use the new password file instead of synchronizing 
		# the old ONTAP users.
		if [ -f /mnt/logs/etc/passwdFlag ] ; then
			mv /mnt/logs/etc/passwd.bak /mnt/logs/etc/passwd
			rm -f /mnt/logs/etc/passwdFlag
		fi

		# Remove support for shadow password and uid of naroot=0
		if [ -f /mnt/logs/etc/passwd ] ; then
			shadow=`grep -c "root:x:0:0:privileged:" /mnt/logs/etc/passwd` ;
			if [ $shadow -eq 1 ] ; then
				echo "Removing Shadow passwd"	
				rm -f /mnt/logs/etc/passwd;
			fi

	        naroot_0=`grep naroot /mnt/logs/etc/passwd | grep -c ":0:6000""` ;
            
            if [ $naroot_0 -eq 1 ] ; then
                echo "Removing root-uid naroot"
                rm -f /mnt/logs/etc/passwd;
            fi

		fi

		# If /mnt/logs/etc/passwd is present, sync ontapusers info from /mnt/logs/etc/passwd to /etc/passwd
		if [ -f /mnt/logs/etc/passwd ] ; then

			# Get group ids for ontapusers and alphagrp
			ontap_users_gid=`awk -F: '$1 == "ontapusers" { print $3 }' /etc/group` 
			alpha_users_gid=`awk -F: '$1 == "alphagrp" { print $3 }' /etc/group`

			# Get SP system users from /etc/passwd
			awk -F: '$4 != '$ontap_users_gid' && $4 != '$alpha_users_gid' { print }' /etc/passwd > /etc/passwd.tmp

			# Get Ontap users and Alpha user from /mnt/logs/etc/passwd
			awk -F: '$4 == '$ontap_users_gid' || $4 == '$alpha_users_gid' { print }' /mnt/logs/etc/passwd >> /etc/passwd.tmp

			rm -f /etc/passwd;
			mv /etc/passwd.tmp /etc/passwd;
			rm -f /etc/passwd.tmp;
		else
			cp /etc/passwd /mnt/logs/etc/passwd;
		fi

		diff /etc/passwd /mnt/logs/etc/passwd;
		
		# If user credentials haven't changed, no need to write to flash
		# Results of diff: $?=0 if files are same, $?=1 if they differ,
		# $?=2 if any file is missing.
		if ! [ $? = 0 ]; then
			rm -f /mnt/logs/etc/passwd.bak;
			# Save backup copy of merged /etc/passwd file in logs partition. 
			# This copy is used if passwd file in logs partition is corrupted.
			cp -f /etc/passwd /mnt/logs/etc/passwd.bak;
			touch /mnt/logs/etc/passwdFlag
			if [ -f /mnt/logs/etc/rebootFlag ]; then
				rm /mnt/logs/etc/rebootFlag;
				reboot;
			fi
			cp -f /etc/passwd /mnt/logs/etc/passwd
			rm -f /mnt/logs/etc/passwdFlag
		fi
		# Look if enabledebug key/value pair is set
		while read line
		do
			case "$line" in
				*enabledebug=on*)
					debug_exist=$(grep -c spdebug /mnt/logs/etc/passwd)
					if [ $debug_exist -eq 0 ] ; then
						echo "spdebug:_J9.....nF3oRovvDxps:60099:60000::/netapp:/bin/sh" >> /mnt/logs/etc/passwd
					fi
				;;
				*) debug_exist=$(grep -c spdebug /mnt/logs/etc/passwd)
					if [ $debug_exist -gt 0 ] ; then
						sed -e '/spdebug/d' /mnt/logs/etc/passwd > /mnt/logs/etc/passwd2
						cp /mnt/logs/etc/passwd2 /mnt/logs/etc/passwd
						rm -rf /mnt/logs/etc/passwd2
					fi
				;;
			esac
		done < /proc/cmdline
		# Make /etc/passwd a link to /mnt/logs/etc/passwd
		ln -sf /mnt/logs/etc/passwd /etc/passwd

		# Removing the symbolic link to /mnt/logs/etc/ssh
		# to avoid corruption in flash partition
		#rm -f /etc/ssh;
		#mkdir /etc/ssh;
		#
		# If /mnt/logs/etc/copyStart is present, it means that keys were not 
		# correctly copied to logs partition during previous boot. We should not 
		# copy the keys over to RAM as the files could be corrupt. The corrupt 
		# files should be deleted. 
		if ! [ -f /mnt/logs/etc/copyStart ]; then
			cp -a /mnt/logs/etc/ssh/* /etc/ssh;
		else
			rm -f /mnt/logs/etc/ssh/*;
			rm -f /mnt/logs/etc/copyStart;
		fi	

		# Disable root login by default
		if [ `grep -c "root\:\*\:" /etc/passwd` == 0 ]; then
			sed 's|^root\:.*\:0\:|root\:\*\:0\:0\:|' /etc/passwd > /etc/passwd.new; 
			mv /etc/passwd.new /mnt/logs/etc/passwd
		fi
	
		# Remove rsa_conf file if present
		if [ -f /mnt/logs/etc/rsa_conf ] ; then
			echo "Removing rsa config file, feature not supported in this release ..."
			rm -f /mnt/logs/etc/rsa_conf
		fi

		# Create /var/log/lastlog file to remove err message
		touch /var/log/lastlog;
		chmod 644 /var/log/lastlog;
		# bump max number of message queues, we need a little more per burt 596776
		echo 48 > /proc/sys/kernel/msgmni

		# Create user home directories
		awk -F : '{print $1, $6}' /etc/passwd | grep home | while read user home; do
			if [ ! -e $home ]; then
				mkdir -p $home
				chown $user: $home
			fi
		done
		;;

	stop)
		;;

	*)

		echo "Usage: local {start|stop}" >&2
		exit 1
		;;

esac
