#!/usr/bin/expect -f
#
# Load kernel and filesystem onto an Auger v2 board attached
# to the serial port.  Some serial program (like "minicom") must already be
# set up to connect.
#
# Usage is: ./loadfs <SERIAL>
#
#--------------------------------------

set KERNEL "zImage.dat"
set FILESYS "voipacfs.bin"

set GATEWAY "192.168.61.161"
set SUBNET  "192.168.61"

set SERIAL "minicom"

#--------------------------------------

log_user 1
exp_internal 0

set sNum [lindex $argv 0]

if { $sNum == "" } { 
    puts "Usage: ./loadfs <SERIAL>"
    exit
}

fconfigure stdin -blocking 1
puts "Loading kernel and filesystem onto Auger board $sNum on serial port."
puts "This is only for use on a NOR-flash-based Voipac PC card."
puts ""
puts "This will erase everything except the bootloader!!!  This procedure"
puts "is OBSOLETE and can result in an unbootable filesystem."
puts ""
puts "ARE YOU SURE YOU WANT TO CONTINUE (y/n)? "
flush stdout
gets stdin ans
if { ($ans != "Y") && ($ans != "y")} {
    puts "OK, aborting."
    exit    
}

spawn $SERIAL
send "\r"
set timeout 2
expect "u-boot> " { send "reset\r" } \
    timeout { puts "Not in u-boot. Press the reset button now..." }

set timeout -1
expect "Hit any key to stop autoboot"

send "s"
expect "u-boot> "

#--------------------------------------
# Set up u-boot variables

puts "Setting up IP addresses..."

send "setenv serverip $GATEWAY\r"
expect "u-boot> "

send "setenv ipaddr $SUBNET.$sNum\r"
expect "u-boot> "

send "printenv\r"
expect "u-boot> " 

send "save\r"
expect "Writing to Flash... done"
expect "u-boot> "

#--------------------------------------
# Erase and load new filesystem

puts "Erasing flash (takes a while)..."

send "erase 1:4-\r"
expect "u-boot> "

puts "Loading kernel via TFTP..."

send "tftpboot $KERNEL\r"
expect "done"
expect "u-boot> "

puts "Saving kernel to flash..."

send "cp.b \x24(fileaddr) 20000 \x24(filesize)\r"
expect "done"
expect "u-boot> "

puts "Loading filesystem via TFTP..."

send "tftpboot $FILESYS\r"
expect "done"
expect "u-boot> "

puts "Saving filesystem to flash (takes a while)..." 

send "cp.b \x24(fileaddr) 160000 \x24(filesize)\r"
expect "done"
expect "u-boot> "

puts "Flash write completed.  Resetting..."
send "reset\r"
expect "login: "

puts "Reboot into Linux succesful!"
puts "Done."

exit

