#!/bin/sh

. "${0%/*}/testlib.sh"

# Skip this test if tools are missing

which socket >/dev/null || exit 77
which timeout >/dev/null || exit 77

# Initialize two nodes

$tinc $c1 <<EOF
init foo
set DeviceType dummy
set Port 32754
set Address localhost
set PingTimeout 1
set AutoConnect no
EOF

$tinc $c2 <<EOF
init bar
set DeviceType dummy
set Port 32755
set PingTimeout 1
set MaxTimeout 1
set ExperimentalProtocol no
set AutoConnect no
EOF

# Exchange host config files

$tinc $c1 export | $tinc $c2 exchange | $tinc $c1 import

$tinc $c1 start $r1
$tinc $c2 start $r2

# No ID sent by responding node if we don't send an ID first, before the timeout

result=`(sleep 2; echo "0 bar 17.7") | timeout 3 socket localhost 32754` && exit 1
test $? = 124
test -z "$result"

# ID sent if initiator sends first, but still tarpitted

result=`echo "0 bar 17.7" | timeout 3 socket localhost 32754` && exit 1
test $? = 124
test "`echo "$result" | head -c 10`" = "0 foo 17.7"

# No invalid IDs allowed

result=`echo "0 foo 17.7" | timeout 1 socket localhost 32754` && exit 1
test $? = 124
test -z "$result"

result=`echo "0 baz 17.7" | timeout 1 socket localhost 32754` && exit 1
test $? = 124
test -z "$result"

# No NULL METAKEYs allowed

result=`printf "0 foo 17.0\n1 0 672 0 0  \n" | timeout 3 socket localhost 32755` && exit 1
test $? = 124
test -z "$result" # Not even the ID should be sent when the first packet contains illegal data

# No splicing allowed

$tinc $c2 stop
$tinc $c2 del ExperimentalProtocol
$tinc $c2 start $r2

./splice foo localhost 32754 bar localhost 32755 17.7 &
sleep 3
test `$tinc $c1 dump reachable nodes | wc -l` = 1
test `$tinc $c2 dump reachable nodes | wc -l` = 1
kill $!

$tinc $c2 stop
$tinc $c1 stop

# Test splicing again with legacy protocol

$tinc $c1 set ExperimentalProtocol no
$tinc $c2 set ExperimentalProtocol no

$tinc $c1 start $r1
$tinc $c2 start $r2

./splice foo localhost 32754 bar localhost 32755 17.0 &
sleep 3
test `$tinc $c1 dump reachable nodes | wc -l` = 1
test `$tinc $c2 dump reachable nodes | wc -l` = 1
kill $!

# Clean up

$tinc $c2 stop
$tinc $c1 stop
