#!/usr/bin/expect -f
#
#  Copyright (c) 2021, The OpenThread Authors.
#  All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#  1. Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#  2. Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#  3. Neither the name of the copyright holder nor the
#     names of its contributors may be used to endorse or promote products
#     derived from this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
#  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
#  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
#  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#  POSSIBILITY OF SUCH DAMAGE.
#

source "tests/scripts/expect/_common.exp"
source "tests/scripts/expect/_multinode.exp"


# The expect on macOS doesn't support `try` or `file tempfile`.
skip_on_macos

file tempfile socat_out
set socat_pid [exec socat -d -d pty,raw,echo=0 pty,raw,echo=0 >/dev/null 2>$socat_out &]
while {true} {
    if {[exec head -n2 $socat_out | wc -l] == 2} {
        set radio_pty [exec head -n1 $socat_out | grep -o {/dev/.\+}]
        set host_pty [exec head -n2 $socat_out | tail -n1 | grep -o {/dev/.\+}]
        break
    }
    sleep 1
}

puts "Radio PTY: $radio_pty"
puts "Host PTY: $host_pty"

set rcp_pid [exec $::env(OT_SIMULATION_APPS)/ncp/ot-rcp 1 < $radio_pty > $radio_pty &]
puts "RCP PID: $rcp_pid"

try {
    spawn_node 1 "rcp" "spinel+hdlc_uart://$host_pty"
    spawn_node 2

    setup_two_nodes "rn" false

    switch_node 2
    set addr [get_ipaddr mleid]

    switch_node 1
    send "ping $addr\n"
    expect "16 bytes from $addr: icmp_seq=1"
    expect_line "Done"
    send "reset\n"
    wait_for "state" "disabled"
    expect_line "Done"
    send "ifconfig up\n"
    expect_line "Done"
    send "thread start\n"
    expect_line "Done"
    wait_for "state" "leader"
    wait_for "ping $addr" "16 bytes from $addr: icmp_seq=\\d+"
    expect_line "Done"
} finally {
    exec kill $rcp_pid
    exec kill $socat_pid
}
