#!/usr/bin/expect
#
# Magnus Damm - version 20151225
# Kuninori Morimoto - version 20151225
#
# Usage do_xls2.expect <port> <loader> <table>
#

set serial_port [lindex $argv 0]
set loader_file [lindex $argv 1]
set table_file [lindex $argv 2]

set timeout 10
set send_slow {10 .001}
log_user 0

proc upload_file {file} {
    set f [open $file]
    set lines [split [read $f] "\n"]
    close $f

    foreach line $lines {
	send -s "$line\n"
    }
}

proc do_xls2 {top flash filename} {
    puts "performing xls2 $top $flash $filename"
    expect {
        timeout { puts "prompt error before xls2"; exit; }
        ">" { send "xls2\r" }
    }
    expect {
        timeout { puts "select error"; exit; }
        "Select (1-3)>" { send "3\r" }
    }
    expect {
        timeout { puts "sw2 all off setting error"; exit; }
        "SW1 SW2 All OFF!  Setting OK? (Push Y key)" { send "Y" }
    }
    expect {
        timeout { puts "sw3 on setting error"; exit; }
        "SW3 ON!  Setting OK? (Push Y key)" { send "Y" }
    }
    expect {
        timeout { puts "top  error"; exit; }
        "  Please Input : H'" { send "$top\r" }
    }
    expect {
        timeout { puts "flash error"; exit; }
        "  Please Input : H'" { send "$flash\r" }
    }
    expect {
        timeout { puts "send error"; exit; }
        "please send ! ('.' & CR stop load)"
    }
    upload_file $filename
    expect -timeout 180 "Clear OK?(y/n)" { send "y" }
    expect {
        timeout { puts "unable to save spi-flash"; exit; }
        "SAVE SPI-FLASH....... complete!"
    }
}

spawn socat STDIO,raw,echo=0 file:$serial_port,raw,echo=0,b57600

expect {
    timeout { puts "time out"; exit; }
    "please send !\r\n"
}

puts "uploading loader file"
upload_file $loader_file

expect -timeout 180 "\r"
expect {
    timeout { puts "no prompt"; exit; }
    ">" { send "\r" }
}

set f [open $table_file]
set lines [split [read $f] "\n"]
close $f

foreach line $lines {
    set comt [string first "#" $line 0]

    if {$comt != -1} {
    	set new_line [string range $line 0 [expr $comt - 1]]
     } else {
    	set new_line $line
     }

    set col [split [string trim $new_line] " "]

    if {[lindex $col 0] == ""} {
    	continue
    }

    do_xls2 [lindex $col 0] [lindex $col 1] [lindex $col 2]
}

exit 0
