#! /bin/sh -e

# Wherever we are, we want to be in daemon/test dir.
cd `git rev-parse --show-toplevel`/daemon/test

. scripts/vars.sh
. scripts/helpers.sh

parse_cmdline 2 "$@"
setup_lightning 2
start_lightningd 2
fund_lightningd

# Prevent anchor broadcast
lcli1 dev-broadcast false
lcli1 connect localhost $PORT2 $FUND_INPUT_TX &

# Expect them to be waiting for anchor, and ack from other side.
check_peerstate lcli1 STATE_OPEN_WAIT_ANCHORDEPTH_AND_THEIRCOMPLETE
check_peerstate lcli2 STATE_OPEN_WAIT_ANCHORDEPTH_AND_THEIRCOMPLETE

# Enable reconnect from here.
DO_RECONNECT=$RECONNECT

$CLI generate 99

# Still waiting.
check_peerstate lcli1 STATE_OPEN_WAIT_ANCHORDEPTH_AND_THEIRCOMPLETE
check_peerstate lcli2 STATE_OPEN_WAIT_ANCHORDEPTH_AND_THEIRCOMPLETE

# Make sure whichever times out first doesn't tell the other.
lcli1 dev-output $ID2 false
lcli2 dev-output $ID1 false
$CLI generate 1

# Node1 should have gone into STATE_ERR_ANCHOR_TIMEOUT.
check "lcli1 getlog debug | $FGREP STATE_ERR_ANCHOR_TIMEOUT"

# Don't try to reconnect any more if we are.
if [ x"$RECONNECT" = xreconnect ]; then DO_RECONNECT=""; fi

# If we're restarting, don't expect peer.
NO_PEER2=1

# Now let them send errors if they're still trying.
lcli2 dev-output $ID1 true || true
lcli1 dev-output $ID2 true || true

# Peer 2 should give up, and have forgotten all about it.
check "lcli2 getlog debug | $FGREP STATE_CLOSED"
check_no_peers lcli2

# Node1 should be disconnected.
check_peerconnected lcli1 false

# Now let node1 broadcast anchor and unilateral close belatedly!
lcli1 dev-broadcast true

# Now mine that transaction so they see it.
$CLI generate 1
check_peerstate lcli1 STATE_CLOSE_ONCHAIN_OUR_UNILATERAL

# Now move bitcoind 1 day, which is what node2 asked for on commit.
# Get current time from last block (works if we run this twice).
CURTIME=$($CLI getblock $($CLI getblockhash $(($BLOCKHEIGHT + 100))) | sed -n 's/ "time": \([0-9]*\),/\1/p')
$CLI setmocktime $(($CURTIME + 24 * 60 * 60))

# Move average so CSV moves.
$CLI generate 6

# Now it should have spent the commit tx.
check_tx_spend

# 100 blocks pass
$CLI generate 100

# Considers it all done now.
check_no_peers lcli1

lcli1 stop
lcli2 stop
all_ok