#!/bin/bash


stty sane
stty erase '^H' echoe echok -echoprt -iexten -ixany
PATH=".:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin"
TERM=linux

DOCSIS=

# Empty for LE, _be for BE
ENDIAN=

if [ $# -ge 1 ]; then
    Arg1="$1"
    TFTP_SERVER=`echo "$Arg1" | cut -f 1 -d ':'`
    CUR_REL=`echo "$Arg1" | sed -n '/\:/p' | cut -f 2 -d ':'`
else
    TFTP_SERVER=stb-irva-01
    CUR_REL=@VERSION@
fi

# JFFS2 only works when the endian of the flash is the same as that of the CPU.
# For the 93730 STBs with a BE flash, we can only use JFFS for now
case  `uname -m` in
#7038)
#JFFS=jffs
#IMAGE="jffs-`uname -m`.img"
#;;
356*|7*|97*)
FSTYPE=jffs2
IMAGE="jffs2-`uname -m`${DOCSIS}${ENDIAN}.img"
;;
93730)
FSTYPE=jffs
IMAGE="jffs-`uname -m`${DOCSIS}${ENDIAN}.img"
;;
esac


echo ""
echo "stbutil v3.9 - Settop configuration utility"
echo "               Copyright (C) 2001,02,03,04 Broadcom Corporation"
echo "               original codes shill@broadcom.com"
echo "               v3.0 tht patched for 2418SR3"
echo "               tht rewritten for 2418sr4,sr5 to support BB"
echo "               v3.5 sr6: tht added support for HD on BB"
echo "               v3.6 on 2.4.25-0: tht added support for Cramfs"
echo "               v3.7 on 2.4.25-0.2: tht Read HD geometry and switch on uname"
echo "               v3.8 on 2.4.25-1.1: tht Integrate with BusyBox 1.0"
echo "               v3.9 on 2.6.12-2.1: jipeng handle input args and tftp error"
echo ""
echo "Usage: stbutil [tftpserver:[subdir]]"
echo "  Please specify an argument to stbutil to override the default."
echo "  Options 1 and 2 will retrieve the $FSTYPE (or cramfs) flash image" $IMAGE "from"
if [ ! -z "$CUR_REL" ]; then
    echo "  $TFTP_SERVER:$CUR_REL/"
else
    echo "  $TFTP_SERVER:/tftpboot"
fi


echo ""
echo "Please select an action:"
echo ""
echo "   1) Create RO root fs on flash with /etc and /var RW on tmpfs (recommended)"
echo "   2) Create root filesystem on flash with no special setup"
echo "   3) Install root filesystem on harddisk"
echo "   4) Create CRAMFS root fs on flash"
echo "   5) Exit"
echo ""
RESPONSE=0

while [ $RESPONSE -lt 1 -o $RESPONSE -gt 5 ]; do
   echo -n "Selection: "
   read RESPONSE
done
#if [ $RESPONSE -eq 3 ]; then
#   stbcfgblk
#   exit 0
#fi
if [ $RESPONSE -eq 3 ]; then

echo "Preparing partition table..."
echo "********************************************************************"
echo "NOTE: When setting up the partition table, it is necessary to create"
echo "      the partitions and reboot the settop. After rebooting, the"
echo "      partitions become usable and the installation can proceed."
echo "********************************************************************"
echo ""
echo ""


# Format /dev/hda4 with EXT2 on HD systems (bcm937xx and bcm97038),
# and with ext3 on all others
   case `uname -m` in
   356*|7112|7312|7319|7328|7402*)
        echo "HD install not applicable to diskless STBs"
    exit 1
    ;;

   *)
    ;;
   esac

HARDDRIVE="hda"
TMP_HARDDRIVE=""
until [ -f /proc/ide/${TMP_HARDDRIVE}/geometry ] ; do

echo "Please provide name of HD [${HARDDRIVE}]"
echo ""

read TMP_HARDDRIVE
if [ "${TMP_HARDDRIVE}" != "" ]; then 
 HARDDRIVE=$TMP_HARDDRIVE
else
 TMP_HARDDRIVE=${HARDDRIVE}
fi 
done

   echo "   Creating new partition table..."
   dd if=/dev/zero of=/dev/${HARDDRIVE} bs=1k count=40960 2> /dev/null

   # THT 6-09-04: Here we have to recalculate the HD geometry if running in 2.4.25 or later
   case "`uname -r`" in
   2.4.18*)
      cat /etc/partition.map | sfdisk -fq /dev/${HARDDRIVE}  2> /dev/null
      ;;
   2.4.25*)
      CHS=`cat /proc/ide/${HARDDRIVE}/geometry|grep logical|cut -f7 -d" "`
      #echo "C/H/S is $CHS"
      Cylinders=`echo $CHS|cut -d/ -f1`
      Heads=`echo $CHS|cut -d/ -f2`
      Sectors=`echo $CHS|cut -d/ -f3`
      echo "C/H/S is $Cylinders/$Heads/$Sectors"
      #TBD: Here we should make sure that the last partition is within $Cylinders
      if [ $Heads -eq 255 ]; then
	     cat /etc/partition-lba48.map | sfdisk -fq /dev/${HARDDRIVE}  2> /dev/null
      else
	     cat /etc/partition.map | sfdisk -fq /dev/${HARDDRIVE}  2> /dev/null
      fi
      ;;
   *)
      cat /etc/partition-lba48.map | sfdisk -fq /dev/${HARDDRIVE}  2> /dev/null
      ;;
   esac

   echo ""
   sleep 2

   echo ""
   echo "Formatting swap partition..."
   mkswap /dev/${HARDDRIVE}2 2> /dev/null

   echo ""
   echo "Enabling swap partition..."
   swapon /dev/${HARDDRIVE}2 2> /dev/null

   echo ""
   echo "Formatting ext3 file systems..."
   mke2fs -j /dev/${HARDDRIVE}1 2> /dev/null
   mke2fs -j /dev/${HARDDRIVE}3 2> /dev/null
   # Supressing periodic fsck
   tune2fs -i 0 /dev/${HARDDRIVE}1 2> /dev/null
   tune2fs -i 0 /dev/${HARDDRIVE}3 2> /dev/null

   case `uname -m` in
   356*|7112|7312|7319|7328)
    echo "HD install not applicable to diskless STBs"
    exit 1
    ;;
   7038*|7400*|7401*|97398|9745*)
    FS=ext2
	mke2fs /dev/${HARDDRIVE}4 -N 4096 -b 4096  2> /dev/null
	tune2fs -i 0 /dev/${HARDDRIVE}4 2> /dev/null
    ;;
   93730)
    FS=ext2
	mke2fs /dev/${HARDDRIVE}4 -N 4096  -b 4096  2> /dev/null
	tune2fs -i 0 /dev/${HARDDRIVE}4 2> /dev/null
    ;;
   7*)
    FS=ext3
   	mke2fs -j /dev/${HARDDRIVE}4 -N 4096  -b 4096 2> /dev/null
   	tune2fs -i 0 /dev/${HARDDRIVE}4 2> /dev/null
    ;;
   *)
    echo "Unknown platform"
    ;;
   esac

   echo ""
   echo "Mounting ${FS} root file systems on /dev/${HARDDRIVE}1 ..."
   if [ ! -d /mnt/hd ]; then
    mkdir /mnt/hd
   fi
   mount -t ${FS} /dev/${HARDDRIVE}1 /mnt/hd 2> /dev/null

echo ""

cd /
# Too bad  the --exclude flag which does not work on directories
tar -cf - `ls   |grep -v '\<mnt\>' |grep -v '\<tmp\>' |grep -v '\<proc\>' |grep -v '\<lost+found\>'` | (cd /mnt/hd; tar xvf -)
mkdir -p /mnt/hd/mnt/nfs
mkdir /mnt/hd/mnt/hd
mkdir /mnt/hd/proc
mkdir /mnt/hd/tmp
mkdir /mnt/hd/opt
mkdir /mnt/hd/data

# Adjust /etc/fstab to reflect how to mount /dev/hda4
mv /mnt/hd/etc/fstab /mnt/hd/etc/fstab.org
cat /mnt/hd/etc/fstab.org | sed 's/\/dev\/hda/\/dev\/'${HARDDRIVE}'/' > /mnt/hd/etc/fstab 
#if [ "$FS" == "ext2" ]; then
#   mv /mnt/hd/etc/fstab.ext2 /mnt/hd/etc/fstab
#   rm /mnt/hd/etc/fstab.*
#else
#   mv /mnt/hd/etc/fstab.ext3 /mnt/hd/etc/fstab
#   rm /mnt/hd/etc/fstab.*
#fi

# Edit init script to mount all HDs
rm /mnt/hd/etc/init.d/rcS
cp /var/tmp/rcS.hd /mnt/hd/etc/init.d/rcS
chmod +x /mnt/hd/etc/init.d/rcS

# jipeng - remove all dhcpcd related files here
rm /mnt/hd/etc/config/dhcpc/dhcpcd*

sleep 5
cd /
umount /mnt/hd

echo ""
echo "************************************************************"
echo "NOTE: After rebooting, edit the files '/etc/resolv.conf' and"
echo "      '/etc/init.d/rcS' to configure your network."
echo "************************************************************"
echo ""
echo "Platform hard drive successfully initialized. You may safely reboot."
echo ""
exit 0

fi
if [ $RESPONSE -eq 4 ]; then
   echo "Installing CRAMFS rootfs"
   echo ""
   IMAGE="cramfs-`uname -m`${DOCSIS}${ENDIAN}.img"
   FSTYPE="cramfs"
   ERASE_FLAG=
fi
if [ $RESPONSE -eq 1 -o $RESPONSE -eq 2 ]; then
   echo "Installing JFFS2 rootfs"
   echo ""
   ERASE_FLAG='-j'
fi
if [ $RESPONSE -eq 5 ]; then
   echo ""
   exit 0
fi
if [ $RESPONSE -eq 1 -o $RESPONSE -eq 2 -o $RESPONSE -eq 4 ]; then
   case "`uname -m`" in
   7315bbx)
      echo "The STB BCM97315-BBX does not support a root file system partition"
      echo "on flash.  Operation aborted"
      exit 1
      ;;

   7115)
     FDEV="/dev/mtd1"
     MTD_DEV="/dev/mtdblock1"
     ;;

   93730)
     FDEV="/dev/mtd1"
     MTD_DEV="/dev/mtdblock1"
     ;;

  356*|7*|97*)
     FDEV="/dev/mtd0"
     MTD_DEV="/dev/mtdblock0"

     ;;
esac


   case "`uname -m`" in
   93730|356*|7*|97*)

     echo ""

     echo "ping -c 4 $TFTP_SERVER"
     ping -c 4 $TFTP_SERVER > ping.err 2>&1
     grep "bytes from" ping.err > /dev/null 2>&1
     if [ "$?" -eq 0 ]; then
   	echo "ping: succeed"
    	rm ping.err
     else
    	cat ping.err;rm ping.err
   	exit 1
     fi

     FDIR=${CUR_REL}

     FLASH_TYPE=`flash_info "$FDEV" |grep Type|cut -f2 -d ':' | cut -f2 -d' ' `
     ERASE_SIZE=`flash_info "$FDEV" |grep Erase|cut -f2 -d ':' | cut -f2 -d' ' `

     echo "Erasing $FLASH_TYPE flash with $ERASE_SIZE kB erase sectors on $FDEV..."
     eraseall $ERASE_FLAG "$FDEV"

     test -d /mnt/flash || mkdir -p /mnt/flash

     # THT 011207: Change to allow support for both NOR and NAND flash co-existing on a board
     # using the same kernel, depending on the chip select
     case "$FLASH_TYPE" in
     NAND*)
     	case "$RESPONSE" in
	1|2)
    		IMAGE="jffs2-${ERASE_SIZE}k-`uname -m`${DOCSIS}${ENDIAN}.img"

     		echo "Fetching flash image ${IMAGE} from ${TFTP_SERVER}:/tftpboot/${CUR_REL}"
     		tftp -gr ${CUR_REL}/${IMAGE} -l /tmp/${IMAGE} ${TFTP_SERVER} &> tftp.err
        		nandwrite -p ${FDEV} /tmp/${IMAGE}
		;;

	4)
  		echo "Fetching flash image ${IMAGE} from ${TFTP_SERVER}:/tftpboot/${CUR_REL}"
     		tftp -gr ${CUR_REL}/${IMAGE} -l /tmp/${IMAGE} ${TFTP_SERVER} &> tftp.err
        		nandwrite ${FDEV} /tmp/${IMAGE}
		# For NAND flash, we can't mount /dev/romblock so quit now
		echo "Copied rootfs to flash complete.  You may now safely reboot"
      		exit 0
		;;
	esac
     ;;

     NOR*) # NOR flashes
    	echo "Fetching flash image ${IMAGE} from ${TFTP_SERVER}:/tftpboot/${CUR_REL}"
    	tftp -gr ${CUR_REL}/${IMAGE} -l ${FDEV} ${TFTP_SERVER} &> tftp.err
     ;;
     esac
     
     if [ `wc -l < tftp.err` -eq "0" ]; then
        rm tftp.err
     else
        echo "tftp: failed to get ${TFTP_SERVER}:/tftpboot/${CUR_REL}/${IMAGE}"
        cat tftp.err;rm tftp.err
        exit 3
     fi

     sleep 2

     if [ $RESPONSE -eq 1 -o  $RESPONSE -eq 2 ]; then
     	echo "Mounting root file system $FSTYPE as $MTD_DEV..."
     	mount -t $FSTYPE "$MTD_DEV" /mnt/flash
     fi
     ;;

   *)
      echo "Unrecognized platform"
      exit 2
      ;;

   esac

   # if Option 2 is selected (Copy rootfs only) we are done
   if [ $RESPONSE -eq 2 -o $RESPONSE -eq 4 ]; then
      umount /mnt/flash
      echo "Copied rootfs to flash complete.  You may now safely reboot"
      exit 0
   fi

   echo "Set up to mount /var and /etc RW"
   cd /mnt/flash/var
   rm -rf /mnt/flash/tmp
   ln -s /var/tmp /mnt/flash/tmp

   # Creating tmpfs images
   dd if=/dev/zero of=/mnt/flash/tmpfsvar.img bs=1024 count=500
   dd if=/dev/zero of=/mnt/flash/tmpfsetc.img bs=1024 count=256
   #
   # Create tarball for var
   #
   cd /mnt/flash/var
   # Create script to mount var RW
   cp /mnt/flash/var/tmp/mountvar.sh /mnt/flash/etc
   chmod +x /mnt/flash/etc/mountvar.sh
   # Substitute with new rc.sysinit script
   cp /mnt/flash/var/tmp/rcS /mnt/flash/etc/init.d/rcS
   rm /mnt/flash/var/tmp/*
   tar -cvf /mnt/flash/var.img . 2>&1 >/dev/null

   #
   # Create tarball for etc
   #
   cd /mnt/flash/etc
   tar -cvf /mnt/flash/etc.img . 2>&1 >/dev/null

   # Clean up
   cd /
   rm -rf /mnt/flash/var/*
   echo ""
   echo "Syncing flash file system..."
   sync; sync
   echo "Unmounting flash file system..."
   echo ""
   umount /mnt/flash
   echo ""

   echo ""
   echo "Finished..."
   exit 0
fi

