#!/bin/sh
# /etc/init.d/rcS: Boot script

source /usr/bin/fcns.shinc

msg()
{
    ( set +x ; echo "`date \"+%Y-%m-%d %H:%M:%S\"`: $*" )
}

checkCfgfs()
{
    # We may want to force the CFGFS to be wiped clean
    if [ -f /cfg/rebuild.jffs2 ]; then
        echo 0
        exit
    fi

    if [ -f /cfg/$JFFS2FILE ]; then
        rm /cfg/$JFFS2FILE
        if [ -f /cfg/$JFFS2FILE ]; then
            #msg "Error: Unable to delete JFFS2 file."
            echo 0
            exit
        fi
    fi

    dd if=/dev/urandom of=/mnt/ramdisk/$JFFS2FILE bs=1024 count=1

    RAMFILE_SIZE=$(stat -c %s /mnt/ramdisk/$JFFS2FILE)
    cp /mnt/ramdisk/$JFFS2FILE /cfg
    JFFS2FILE_SIZE=$(stat -c %s /cfg/$JFFS2FILE)
    if [ "$RAMFILE_SIZE" != "$JFFS2FILE_SIZE" ]; then
        #msg "File as it exists in RAM is a different size than on JFFS2!"
        #msg "RAM: $RAMFILE_SIZE, CFG: $JFFS2FILE_SIZE"
        echo  0
    else
        echo 1
    fi

    rm -f /cfg/$JFFS2FILE
    rm -f /mnt/ramdisk/$JFFS2FILE
}

# =====================================================================
# Macro to log McPost Events
# $1 - name of the MC Post item
# $2 - MC Post id number
# $3 - MC Post Status
# $4 - MC Post Failure Reason
# $5 - MC Post Failure Reason 2
# =====================================================================
logMcPost()
{
    set +x
        echo "[$1]"                 >> /mem/mc_post.out
        echo "event=533"            >> /mem/mc_post.out
        echo "idNumber=$2"          >> /mem/mc_post.out
        echo "status=$3"            >> /mem/mc_post.out
        echo "failureReason=$4"     >> /mem/mc_post.out
        echo "failureReason2=$5"    >> /mem/mc_post.out
        echo ""                     >> /mem/mc_post.out
    set -x
}

testMcFlash()
{
    msg "******************* Testing Flash Drive *******************"

    FLASH_POST_REASON=0

    dd if=/dev/sda of=/dev/null count=1 2>&1 > /dev/null

    if [ $? -eq 0 ]
    then
        mkdir -p /mnt/flashdisk
        mount /dev/sda1 /mnt/flashdisk
        if [ $? -eq 0 ]
        then
            ls -l /mnt/sda1
            FLASH_POST_STATUS=1
        else
            FLASH_POST_STATUS=2
            FLASH_POST_REASON=21
        fi
    else
        msg "Flash Drive Error"
        FLASH_POST_STATUS=0
        FLASH_POST_REASON=20
    fi

    logMcPost FLASH 1 $FLASH_POST_STATUS $FLASH_POST_REASON 0
}

# =====================================================================
# $1 - returns:  variable name to place true/false status
# =====================================================================
checkPrepI2c()
{
    # workaround:  some systems seem to not communicate at first.
    # Run a couple of commands to prime the pump.
    local rc=0
    for i1 in $(seq 0 2); do
        results=$(i2c-codeload --target cpld --currinfo 2>&1)
        rc=$?
        [ "$rc" -eq 0 ] && break

        sleep 0.8
    done

    local isWorking
    [ "$rc" -eq 0 ] && isWorking=true || isWorking=false
    eval "$1=$isWorking"
}

checkCPLD()
{
    msg "******************* Testing CPLD Version *******************"
    # assume success
    local POST_STATUS=0
    local POST_FAIL_REASON=0

    local rc=0
    cpldrev=$(i2c-codeload --target cpld --probe)
    rc=$?
    if [ "$rc" -ne 0 ]
    then
        msg "I2C Error probing the CPLD"
        POST_STATUS=1
        POST_FAIL_REASON=1
        logMcPost CPLD 3 $POST_STATUS $POST_FAIL_REASON 0
    fi
}
testI2c()
{
    local i2cIsWorking
    msg "******************* Testing I2C Connect *******************"

    # assume success
    local POST_STATUS=1
    local POST_FAIL_REASON=0

    checkPrepI2c i2cIsWorking
    if ! $i2cIsWorking; then
        i2c-codeload --target cpld --currinfo
        msg "I2C Error communicating to CPLD"

        POST_STATUS=0
        POST_FAIL_REASON=20
    fi
    logMcPost I2C 3 $POST_STATUS $POST_FAIL_REASON 0
}

# =====================================================================
# $1 - name of the mtd partition to rebuild (e.g. log or cfg)
# $2 - name of the status variable.  Returns:  true or false
# =====================================================================
rebuildjffs2()
{
    local part=$1
    local rc=false

    local mtdsize
    local mtdnbr

    # variables from:  genAllMtdPropVariables "$(cat /proc/moose/mtd)"
    eval mtdsize=\$mtdsize_$part
    eval mtdnbr=\$mtdnbr_$part

    local tmpFile=/mnt/ramdisk/tmp.jffs2
    rm -f $tmpFile

    msg "Rebuilding JFFS2 Filesystem"
    local tgtsize=$((0x$mtdsize))

    rm -rf /mnt/ramdisk/empty
    mkdir -p /mnt/ramdisk/empty
    msg "Creating new JFFS2 filesystem."
    mkfs.jffs2 --eraseblock=131072 --pad=$tgtsize --root=/mnt/ramdisk/empty --output=$tmpFile

    if [ -f "$tmpFile" ]; then
        local mntStr=$(mount | grep /dev/mtd$mtdnbr)
        if [ -n "$mntStr" ]; then
            msg "Unmounting JFFS2 partition"
            sleep 2
            umount -f /dev/mtd$mtdnbr
        fi

        mntStr=$(mount | grep /dev/mtd$mtdnbr)
        if [ -n "$mntStr" ]; then
            msg "Application has /$part open!"
            msg "`ps`"
            msg "`lsof | grep $part`"
        else
            msg "Writing new filesystem to flash memory"
            dd if=$tmpFile of=/dev/mtd$mtdnbr bs=128k
            msg "Mounting /dev/mtd$mtdnbr"
            mount -t jffs2 /dev/mtd$mtdnbr /mnt/$part

            mntStr=$(mount | grep /dev/mtd$mtdnbr)
            if [ -n "$mntStr" ]; then
                rc=true;    # success
            fi
        fi
    fi

    rm -f "$tmpFile"
    rm -rf /mnt/ramdisk/empty
    eval $2="$rc"
}

removelogs()
{
    msg "Attempting to delete files from CFG to reclaim space"
    cd /cfg/log
    rm *.log
    cd - >> /dev/null
}

checketh0()
{
    echo "----- before checketh0" >>/mem/eth0stat
    ethtool eth0 >>/mem/eth0stat
    LINK_STATUS=$(ethtool eth0 | grep -c "Link detected: yes")
    if [ $LINK_STATUS != 0 ]
    then
        echo "eth0: link status ok"
        touch /mem/eth0linkok
    else
        echo "eth0: link status fail"
        touch /mem/eth0linkfail
        # fix it
        ethtool -s eth0 advertise 0x03F autoneg on
        sleep 5
        LINK_STATUS=$(ethtool eth0 | grep -c "Link detected: yes")
        if [ $LINK_STATUS != 0 ]
        then
            echo "eth0: link status ok"
        else
            echo "eth0: link status fail again"
        fi
    fi
    echo "----- after checketh0" >>/mem/eth0stat
    ethtool eth0 >>/mem/eth0stat
}

# =====================================================================
# (Replaces old ckfsjffs2.c application)
# $1 - name of the mtd partition to read
# $2 - name of the status variable.  Returns:  true or false
# =====================================================================
ckHdrJffs2()
{
    local firstBytes=$(head -c 12 $1 | hexdump -C)
    firstBytes="${firstBytes#*  }";     # cut preface
    firstBytes="${firstBytes%%   *}";   # cut suffix
    firstBytes="${firstBytes//  / }";   # make all spacing uniform

    # Remove JFFS2 "nodetype" short from consideration because a node
    # can be in several different valid states
    local magicBitmask="${firstBytes:0:5}"
    local lengthAndCrc="${firstBytes:12}"

    local isOK=false
    if [ "$magicBitmask" == "85 19" ] \
       && [ "$lengthAndCrc" == "0c 00 00 00 b1 b0 1e e4" ]; then
        isOK=true
    fi
    eval $2="$isOK"
}

mountFsLog()
{
    msg "Mount log"
    status=true
    ckHdrJffs2 /dev/mtd$mtdnbr_log cfgIsOK
    if $cfgIsOK; then
        mount -t jffs2 /dev/mtd$mtdnbr_log /mnt/log
        if [ "$?" -ne "0" ]; then
            rebuildjffs2  log  status
        fi
    else
        rebuildjffs2  log  status
    fi
    if ! $status; then
        msg "ERROR: Cannot mount log jffs2 file system"
    fi
}

mountFsCfg()
{
    msg "Mount cfg"
    needRebuild=false
    ckHdrJffs2 /dev/mtd$mtdnbr_cfg cfgIsOK
    if $cfgIsOK; then
        mount -t jffs2 /dev/mtd$mtdnbr_cfg /mnt/cfg
        if [ "$?" -eq "0" ]; then
            # Sanity check of the JFFS2 filesystem
            if [ "$(checkCfgfs)" -eq "0" ]; then
                removelogs
                if [ "$(checkCfgfs)" -eq "0" ]; then
                    needRebuild=true
                fi
            fi
        else
            needRebuild=true
        fi
    else
        needRebuild=true
    fi

    status=true
    if $needRebuild; then
        rebuildjffs2  cfg  status
        msg "Restoring system defaults"
        /app/default/restoreDefaults.sh factory noreboot
        echo `date` >> /cfg/self.healed
    fi

    if ! $status; then
        msg "ERROR: Cannot mount cfg jffs2 file system"
    fi
}

# =====================================================================
# Write-Protect critical partitions. They are only written-to at
# codeload time.
# =====================================================================
writeProtectSomeMtds()
{
    if [ -z "$mtdnbr_kernel" ]; then
        genAllMtdPropVariables "$(cat /proc/moose/mtd)"
    fi

    # get a list of all the partitions to protect
    local allReadOnly="$(cat /proc/moose/mtd-readonly)"

    # remove all blanks and double-quotes
    allReadOnly=${allReadOnly// /_}
    allReadOnly=${allReadOnly//\"/}

    for part in $allReadOnly; do
        eval partNbr=\"\$mtdnbr_$part\"

        # All work done on temporary unbuffered mtd partition
        local unbufPart="/dev/mtd${partNbr}Unbuf"
        rm -f $unbufPart
        mknod $unbufPart c 90 $((partNbr*2))

        # Suppress errors: SPI flash not working at initial release
        flash_lock $unbufPart 0 -1 &> /dev/null

        rm -f $unbufPart
    done
}

# =====================================================================
# Rotate existing log files by renaming them.  Emulates the logic
# that busybox syslogd uses for option "-b xxx".  Note that the Linux
# standard (https://wiki.archlinux.org/index.php/Logrotate) is to start
# at file extension ".1".  Busybox starts at file extension ".0"
# $1 - Full path name of base log file
# $2 - Maximum number of logs to retain
# =====================================================================
rotateLogs()
{
    local logFolder="${1%/*.*}"
    local baseName="${1##*/}"
    local maxLogs=$2

    cd "$logFolder"

        for i1 in $(seq $((maxLogs-1)) -1 0); do
            # move logs to older (larger #).  Start w/ oldest that we want to keep
            [ -f "$baseName.$i1" ] && mv -f "$baseName.$i1" "$baseName.$((i1+1))"
        done

        [ -f "$baseName" ] && mv -f "$baseName" "$baseName.0"

    cd -
}

# =====================================================================
# clean a log file from /log
# will clean the oldest log file that fist the pattern
# $1 - pattern
# =====================================================================
cleanLogFile()
{
    local pattern=$1

    for i in $(ls -1 -t $pattern | tac)
    do
        msg "removing $i"
        rm -f $i
        return
    done
}

# =====================================================================
# will return the percent full of the log fs
# $1 - return variable
# =====================================================================
logFSSize()
{
    eval $1=`df /mnt/log | grep /mnt/log | awk '{ printf("%d",$5); }'`
}

# =====================================================================
# check to see if log filesystem is full, and clean up some stuff if it is
# no args
# =====================================================================
checkLogFull()
{
    local LOGFSSIZE=0
    logFSSize LOGFSSIZE
    # we try to retain as much as possible, yet stay away from being too close to full
    threshold="80"
    count="0"
    while [  ${LOGFSSIZE} -gt $threshold ];
    do
        # so that we don't run away, doing this forever, we limit the scope
        let count++
        if [ $count -gt 20 ]
        then
            break
        fi

        msg "cleaning up log files in /log, ${LOGFSSIZE}% full"
        cleanLogFile "/mnt/log/os/systrack/sys*.out"
        logFSSize LOGFSSIZE
    done
    msg "/log limits ${LOGFSSIZE}% utilization)"
}

RAMDISKSIZE="128m"

JFFS2FILE=fs.check
SERIAL_SPEED="4000000"
MTU="4096"

msg "Mounting /proc filesystem"
mount -t proc proc /proc

msg "Mounting /sysfs filesystem"
mount -t sysfs sysfs /sys

msg "Mounting devpts terminal device filesystem"
mount -n -t devpts -o mode=620 devpts /dev/pts

msg "Mounting debugfs"
mount -t debugfs none /sys/kernel/debug

isEngMode eMode

msg "Get the drivers/modules up"
modprobe msgdrv
modprobe mcscbridge
modprobe mooseproc
modprobe mcfulink


# Install USB Serial drivers
mknod /dev/ttyGS0 c 254 0

# Get the serial number for the USB Serial port, needed for Windows 2012
getMacAddr  __serial
modprobe ocores-udc
modprobe g_serial use_acm=1 iSerialNumber=$__serial

msg "Change auto flush filesystem cache from 30 to 1 secs"
echo 100 > /proc/sys/vm/dirty_writeback_centisecs
echo 100 > /proc/sys/vm/dirty_expire_centisecs
echo 3 > /proc/sys/vm/dirty_ratio
echo 3 > /proc/sys/vm/dirty_background_ratio
echo 0 > /proc/sys/vm/swappiness

msg "Determine the MTD layout"

# Following creates variables like:  mtdnbr_app, mtdnbr_log, mtdnbr_cfg, etc.
genAllMtdPropVariables "$(cat /proc/moose/mtd)"
set | grep "mtd" | sort

msg "Create ramdisk"
ramdisk $RAMDISKSIZE /mnt/ramdisk

msg "Mount app"
mount -t squashfs /dev/mtd$mtdnbr_app /mnt/app1

# mount jffs2 partitions, but w/ error recovery logic
isRunningFromSpi isSpi
if $isSpi; then
    mountFsLog
fi
mountFsCfg

checkLogFull

ramdisk 8m /mnt/mem
ln -s /mnt/mem /mem
mkdir /mem/log

readsystemtime
msg "init: read system time from file"
logger "init: read system time from file"
timed &

# Test components
# test usb flash drive removed due to soft reset issues
# testMcFlash;    # MC Flash Drive
# test i2c-to-cpld connection removed due to cpld jtag issues
# probe the CPLD here
checkCPLD

msg "Set up symbolic links"
rm /app

getMacAddr  __serial; # returns val to this variable
msg "serial number: $__serial"

# Get ethernet working before trying to use NFS mounting of app/
msg "init: Initializing network interfaces lo, eth0"
logger "init: Initializing network interfaces lo, eth0"

ifup lo
networking.srv restart
echo "----- after networks.srv restart" >>/mem/eth0stat
ethtool eth0 >>/mem/eth0stat

export TARGET_APP=/mnt/app1

if [ -f /cfg/etc/config/mountnfs.shinc ]; then
    # User can override TARGET_APP to point to nfs mounted folder
    source /cfg/etc/config/mountnfs.shinc
fi

# Copy /cfg/version.txt *after* any override of /app.  Otherwise, you may not
# be able to login as 'root'.  This can happen if version.txt comes from the flash
# file system but the current, running MC App is on an NFS mounted folder.

if [ -f $TARGET_APP/mc_system_version.txt ]
then
    # we were able to read the contents of the current app
    export APP_VALID=true
    FILESIZE=$(stat -c%s "/cfg/version.txt")
    if [ ! -f /cfg/version.txt ] || [ $FILESIZE -eq 0 ]; then
        # initialize if not already exists
        cp $TARGET_APP/mc_system_version.txt /cfg/version.txt
    else
        # Assure that version is correct - Required for NFS debugging
        actualVersion=$(inicntrl $TARGET_APP/mc_system_version.txt MC_system version)
        inicntrl /cfg/version.txt MC_system version $actualVersion
    fi
fi

msg "link $TARGET_APP as /app"
ln -s $TARGET_APP /app
rm -rf /opt
msg "link $TARGET_APP/opt as /opt"
ln -s $TARGET_APP/opt /opt

# Redirect (via /etc/syslog.conf) msgs to FLASH
# NOTE: /var/log/ is empty at boot time (it's RAM)
mkdir -p /log/os/
mkdir -p /log/os/systrack
ln -sf /log/os/messages    /var/log/messages

# Create symlinks to every possible file created by log rotation
logRotation=10

for i1 in $(seq 0 $((logRotation-1))); do
    ln -sf /log/os/messages.$i1  /var/log/messages.$i1
done

syslogd -f /etc/syslog.conf -b $logRotation &
klogd -c 1 &

msg "init: System logging initiated"
logger "init: System logging initiated"
crond
msg "init: Crond started"
logger "init: Crond started"

set -x

NETWORK_VERSION=$(xmlcntrl /app/relinfo/release.xml release networkVersion)
BOARD_CFG=$(cat /proc/moose/cpld/board_config)

# If network version was not in the releases.xml file
# Use the board type to determine network version

if [ -z "$NETWORK_VERSION" ]
then
    BOARD_TYPE=$(cpldtype)
    # Is this a Gallium board ?
    if [ $BOARD_TYPE -eq 348 ]
    then
        case $BOARD_CFG in
            # Is this a FX controller (herc or atlas) ?
            2)  NETWORK_VERSION=v2
                ;;
            # default to version 1 (HP Gallium)
            *)  NETWORK_VERSION=v1
                ;;
        esac

    else
        # Titanium or Chromium
        NETWORK_VERSION=v0
    fi
fi

# If the network version file exists?
if [ -e /etc/networking-$NETWORK_VERSION.xml ]
then
    msg "Using $NETWORK_VERSION networking addresses"
    cp /etc/networking-$NETWORK_VERSION.xml /etc/networking.xml
else
    # error msg
    msg "There is  no /etc/networking-$NETWORK_VERSION.xml file"
fi

# Set the platform information cache size
if [ $BOARD_CFG -eq 2 ]
then
    xmlcntrl /etc/platform.xml release CACHE_16G true
else
    xmlcntrl /etc/platform.xml release CACHE_16G false
fi

set +x

A_MCMC_IP=$( xmlcntrl /etc/networking.xml CONTROLLER_A mcmc_ip )
A_MCMC_MASK=$( xmlcntrl /etc/networking.xml CONTROLLER_A mcmc_mask )

B_MCMC_IP=$( xmlcntrl /etc/networking.xml CONTROLLER_B mcmc_ip )
B_MCMC_MASK=$( xmlcntrl /etc/networking.xml CONTROLLER_B mcmc_mask )

A_SL_IP=$( xmlcntrl /etc/networking.xml CONTROLLER_A sl0_ip )
A_SL_MASK=$( xmlcntrl /etc/networking.xml CONTROLLER_A sl0_mask )

B_SL_IP=$( xmlcntrl /etc/networking.xml CONTROLLER_B sl0_ip )
B_SL_MASK=$( xmlcntrl /etc/networking.xml CONTROLLER_B sl0_mask )

currentslot=$(readslot)
if [ "$currentslot" == "A" ]
then
    echo "$B_SL_IP  othermc_slip" >> /etc/hosts
    echo "$B_MCMC_IP  othermc" >> /etc/hosts
    echo "$B_MCMC_IP  othermcinner" >> /etc/hosts
    echo "$A_SL_IP  mymc_slip" >> /etc/hosts
    echo "$A_MCMC_IP  mymcinner" >> /etc/hosts
    IP_ADDR_OTHER=`xmlcntrl /cfg/sysinfo/system.xml MCBInfo ipV4Address`
    echo "$IP_ADDR_OTHER othermcouter" >>/etc/hosts
    # set the MAC
    xmlcntrl /cfg/sysinfo/system.xml MCAInfo macAddress $__serial
else
    echo "$A_SL_IP  othermc_slip" >> /etc/hosts
    echo "$A_MCMC_IP  othermc" >> /etc/hosts
    echo "$A_MCMC_IP  othermcinner" >> /etc/hosts
    echo "$B_SL_IP  mymc_slip" >> /etc/hosts
    echo "$B_MCMC_IP  mymcinner" >> /etc/hosts
    IP_ADDR_OTHER=`xmlcntrl /cfg/sysinfo/system.xml MCAInfo ipV4Address`
    echo "$IP_ADDR_OTHER othermcouter" >>/etc/hosts
    # set the MAC
    xmlcntrl /cfg/sysinfo/system.xml MCBInfo macAddress $__serial
fi

# disable driver by touching /cfg/disablemcmc
if [ ! -e /cfg/disablemcmc ]
then
    modprobe mcmclink
fi

slattach -L -F -s 115200 -p cslip /dev/ttyS1 &
sleep 2

#set up the inter-MC communication
msg "init: initialize mcmc link"
logger "init: initialize mcmc link"
mc=`readslot`
if [ "$mc" == "A" ]
then
    ifconfig mcmc $A_MCMC_IP dstaddr $B_MCMC_IP netmask $A_MCMC_MASK
    ifconfig sl0  $A_SL_IP pointopoint $B_SL_IP up
else
    ifconfig mcmc $B_MCMC_IP dstaddr $A_MCMC_IP netmask $B_MCMC_MASK
    ifconfig sl0  $B_SL_IP pointopoint $A_SL_IP up
fi

# dump network config to boot log
networking.srv show

source /etc/profile

# start timec to obtain time from mouse or other MC
timec othermc &

msg "init: Starting base services"
logger "init: Starting base services"

msg "init: spawner"
logger "init: spawner"
spawner

# start outertrack
msg "init: outertrack"
logger "init: outertrack"
outertrack

set +x
engModeIssue=
if [ $APP_VALID == "true" ]
then
    # app fs is valid, defer starting telnet/ftp until rcS2 script
    msg "app valid"
    # now were going to set the user passwd to lock things down
    if [  -f /cfg/no.root.genpw  -a  "$eMode" == "true"  ]
    then
        msg "developer system, no auto passwd on root or mui"
        engModeIssue="Engineering Build: enabled"
    else
        msg "locking down root and mui user"
        APPVER=`inicntrl /app/mc_system_version.txt MC_system version`
        if [ "$APPVER" == "" ]
        then
            APPVER="none"
        fi
        __key3=`echo $APPVER | rev`
        __key4=`echo $__serial | rev`
        msg "using: [$__serial] [$APPVER]"
        genpw -a -u root -k1 $__serial -k2 $APPVER -k3 $__key3

        if [ -f /cfg/no.root.genpw ]
        then
            msg "developer system, no auto passwd on mui"
            engModeIssue="Engineering Build: mui"
        else
            scsivendorid=$(xmlcntrl /cfg/sysinfo/system.xml system scsiVendorId)
            if [ "$scsivendorid" == "Stratus" ]
            then
                msg "setting stratus mui password"
                genpw -a -u mui -p stratusmui
            else
                genpw -a -u mui -k1 $__serial -k2 $APPVER -k3 $__key4
            fi
        fi
    fi
    genpw -a -u restoredefaults -p $__serial
    genpw -a -u restoreusers -p $__serial
else
    msg "neither app is valid, set up for get out of jail capability"
    msg "init: telnted starting"
    logger "init: telnted starting"
    telnetd
    msg "init: pure-ftpd starting"
    logger "init: pure-ftpd starting"
    pure-ftpd -4 -B -E -G -c 5 -C 5
    msg "adding ftp user for login"
    echo "ftp:\$1\$LSJkdfRI\$4WvZVeEnya5wLnAXkuXkF/:2:2:Linux User,,,:/mnt/ramdisk:/bin/sh" >>/etc/passwd
fi

#start the http daemon
export IF_DEBUG_DISABLE=`xmlcntrl /cfg/sysinfo/system.xml system debugDisable`
if [ "$IF_DEBUG_DISABLE" == "false" ]
then
    msg "init: starting httpd debug server"
    httpdlite.srv start debug
fi

echo "----- after httpd" >>/mem/eth0stat
ethtool eth0 >>/mem/eth0stat

# Protection mechanism: mtd0Verify is used by the memtracker
# to continuously check the integrity of the boot command
# (And fix it if necessary).
mknod /dev/mtd0Verify c 90 0
flash_lock /dev/mtd0Verify 0 -1
strings /dev/mtd0Verify > /tmp/mtd0.txt
grep -q bootcmd /tmp/mtd0.txt
if [ $? -eq 0 ]
then
    cp /tmp/mtd0.txt /cfg/mc_boot_meta.txt
elif [ -f /cfg/version.txt ]
then
    zImageSize=`inicntrl /cfg/version.txt zImage size`
    initRamFsSize=`inicntrl /cfg/version.txt initramfs_gz size`
    printf "# Created by rcScont\nbootcmd=boot linux sf/00600000/%x sf/00900000/%x\n" $zImageSize $initRamFsSize > /tmp/mtd0.txt
    cp /tmp/mtd0.txt /cfg/mc_boot_meta.txt
else
    msg "init: ERROR: Unable to create mc_boot_meta file!"
fi

msg "init: start systracker"
systrack &

ethtool eth0 >>/mem/eth0stat

if [ -f /cfg/sysinfo/system.xml ]
then
    export IF_ACT_DISABLE=`xmlcntrl /cfg/sysinfo/system.xml system activityProgressDisable`
    if [ $IF_ACT_DISABLE == "false" ]
    then
        msg "Starting Activity Progress Reporting"
        /app/etc/init.d/httpd-progressS start &
    else
        msg "Activity Progress Reporting - not enabled"
    fi
else
    # unconditionally start
    msg "Recovery - Starting Activity Progress Reporting"
    httpdlite.srv start progress
fi

# RPC server and portmapper for RPC communications for GL145 and GL240
local mc_sys_version
mc_sys_version=`inicntrl /cfg/version.txt MC_system version`

mc_sys_version_string=${mc_sys_version:0:5}

if [ "$mc_sys_version_string" == "GLM24" ]
then
    msg "init: portmap and rpcd starting"
    logger "init: portmap and rpcd starting"
    portmap
    sleep 1
    rpcd &
else
    msg "Not starting rpcd: App Version: "$mc_sys_version
    logger "Not starting rpcd: App Version: "$mc_sys_version
fi

echo "----- after portmap/rpcd" >>/mem/eth0stat
ethtool eth0 >>/mem/eth0stat


# socket server for PFU file transfers
msg "init: pfud starting"
logger "init: pfud starting"
pfud &
# move this to later, the rcS2 script
#  dopfu &

echo "----- after pfud" >>/mem/eth0stat
ethtool eth0 >>/mem/eth0stat

# watcherd process keeps HW watchdog entertained and monitors soft watchdogs
msg "init: watcherd starting"
logger "init: watcherd starting"
LD_LIBRARY_PATH=/opt/lib:$LD_LIBRARY_PATH watcherd &
#watcherd &

echo "----- after watcherd" >>/mem/eth0stat
ethtool eth0 >>/mem/eth0stat

# enable ping broadcast based on sysinfo
setpingbroadcast

echo "----- after setpingbroadcast" >>/mem/eth0stat
ethtool eth0 >>/mem/eth0stat

# print out version information on serial port
echo "System Version: $(inicntrl /cfg/version.txt system_bundle version)
MC Version: $(inicntrl /cfg/version.txt MC_system version)
Serial Number: $__serial" > /etc/issue

[ -n "$engModeIssue" ] && echo "$engModeIssue" >> /etc/issue

# symlink the banner and executables for chroot'd FTP server
cd /mnt/ramdisk
ln -s /etc/.banner .banner
ln -s /usr/bin/docodeload
ln -s /usr/bin/doloadlicense
ln -s /usr/bin/getlogs
ln -s /usr/bin/getperf
ln -s /usr/bin/getManagedLogs
ln -s /usr/bin/getftpmanagedlogs
ln -s /usr/bin/getmcinfo
ln -s /usr/bin/cplddowngrade
ln -s /usr/bin/runactivity
cd - >> /dev/null

# Allow "ping" to be called within a script in chroot'd FTP server
chmod u+srwx,go=rx /bin/ping

echo "----- end of rcScont" >>/mem/eth0stat
ethtool eth0 >>/mem/eth0stat
set -x


# start ntp if configured
logger "init: getting/setting system clock (NTP or CAPI)"
systime.srv start

# Do this after filesystems are mounted
writeProtectSomeMtds

# Log linux msgs directly to /log while flashing: everything else is unmounted
mkdir -p /log/os/codeload
ln -sf   /log/os/codeload    /var/log/codeload

# Save to FLASH and rotate logs for both app.out and boot.out
startupFolder=/log/os/startup
mkdir -p $startupFolder
ln -sf $startupFolder    /var/log/startup

fileAppOut="$startupFolder/app.out"
fileBootOut="$startupFolder/boot.out"

rotateLogs "$fileAppOut"  4
rotateLogs "$fileBootOut" 4

# cleanup old logs that are not needed anymore
rm /cfg/outer*.out

msg "init: spawndog"
logger "init: spawndog"
spawndog

for file in $(ls /log/os/sysd*) $(ls /log/os/preprestart.log*); do
    if [ `stat $file -c%s` -gt 320000 ]; then
        rm -f $file
    fi
done

msg "start application startup script"
# run the next part in the background for now, so that we get a prompt sooner
logger "init: Calling next rcS script"
if [ -e /cfg/etc/init.d/rcS2 ]
then /cfg/etc/init.d/rcS2 >$fileAppOut &>$fileAppOut &
elif [ -e /app/etc/init.d/rcS2 ]
then /app/etc/init.d/rcS2 >$fileAppOut &>$fileAppOut &
fi

sysd -d "ECComponent|ConfigNoticeWatcher"

# KEEP THIS AS LAST LINE IN THE SCRIPT
mv -f /var/log/boot.out $fileBootOut
