#!/usr/bin/env dash

# Don't use bash: it has a bug in its handling of 'alias'.

set -x
set -e

killall main.exe || true

bake () {
    sleep 1
    tezos-client bake for bootstrap1 1> /dev/null 2>&1
    sleep 1
}

src/bin_node/tezos-sandboxed-node.sh 1 1> /tmp/node1.log 2>&1 &
src/bin_node/tezos-sandboxed-node.sh 2 1> /tmp/node2.log 2>&1 &
sleep 5
eval $(./src/bin_client/tezos-init-sandboxed-client.sh 1)
sleep 3
tezos-activate-alpha

BOOTSTRAP1=tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx
export BOOTSTRAP1
tezos-client originate contract fa1.2 transferring 100 from bootstrap1 \
             running fa1.2.tz \
             --init "Pair {Elt \"$BOOTSTRAP1\" (Pair {} 100000000000000)} 100000000000000"\
             --burn-cap 3 1> /tmp/log 2>&1 &
bake
FA12=$(grep 'New contract' /tmp/log | cut -f3 -d' ')
echo FA12 is $FA12

tezos-client originate contract dex transferring 0 from bootstrap1 \
             running /home/yann/dev/gas-optimisation/gas-measures/dexter.tz \
             --init "Pair {} (Pair (Pair (Pair False 1000000) (Pair \"$BOOTSTRAP1\" False)) (Pair (Pair \"$FA12\" 1000000) 1000000))" \
             --burn-cap 3 1> /tmp/log 2>&1 &
bake
DEX=$(grep 'New contract' /tmp/log | cut -f3 -d' ')

echo DEX is $DEX

tezos-client transfer 0 from bootstrap1 to fa1.2 \
     --entrypoint approve \
     --arg "(Pair \"$DEX\" 1000000)" \
     --burn-cap 3 1> /tmp/log 2>&1 &
bake

tezos-client transfer 1 from bootstrap1 to dex \
             --entrypoint addLiquidity \
             --arg "(Pair (Pair \"$BOOTSTRAP1\" 1) (Pair 1000000 \"2050-01-29T18:00:00Z\"))" \
             --burn-cap 3 1> /tmp/log 2>&1 &
bake

tezos-client transfer 1 from bootstrap1 to dex \
     --entrypoint xtzToToken \
     --arg "(Pair \"$BOOTSTRAP1\" (Pair 1 \"2050-01-29T18:00:00Z\"))" \
     --burn-cap 3 1> /tmp/log 2>&1 &
bake

cat /tmp/log