#!/bin/bash

## ------------------------ NO CHANGES BELOW ---------------------- ##
# (it ain't pretty but it works™)
FETCH () {
    local DESTINATION=$1
    local SOURCE=$2
    echo "# Fetching implementation 'DESTINATION'.."
    local DESTINATION_DIR=$(dirname "$DESTINATION")
    mkdir -p "$DESTINATION_DIR"
    curl $SOURCE > "$DESTINATION"
}
BUILD () {
    echo "# Compiling contracts.."
    forge build
}
RECORD_START () {
    # Create a file containing all of these contract's addresses as constants
    echo "// SPDX-License-Identifier: MIT" > /tmp/addresses.sol.tmp
    echo "// Automatically generated by build.sh" >> /tmp/addresses.sol.tmp
    echo "pragma solidity >=0.5.0;" >> /tmp/addresses.sol.tmp
    # Record all transactions made with etheno in the background
    etheno --ganache --ganache-args "--deterministic --gasLimit 10000000" -x /tmp/echidna-init.json &
    ETHENO_PID=$!
    sleep 5
}
DEPLOY () {
    local FILE=$1
    local CONTRACT=$2
    local GANACHE_KEY="0xf2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d"
    local ETHENO_URL="http://127.0.0.1:8545/"
    echo "# Deploying '$CONTRACT' to etheno.."
    # Use foundry to deploy contracts via etheno
    CONTRACT_ADDRESS=$(forge create --legacy --rpc-url "$ETHENO_URL" --private-key $GANACHE_KEY "$FILE:$CONTRACT" | grep "Deployed to")
    CONTRACT_ADDRESS=${CONTRACT_ADDRESS#Deployed to: 0x}
    echo "address constant $CONTRACT = address(0x00$CONTRACT_ADDRESS);" >> /tmp/addresses.sol.tmp # we don't get addresses with valid checksums from forge, workaround with 00 prefix
}
RECORD_END () {
    # Finish address constants file
    rm ./src/test/addresses.sol
    mv /tmp/addresses.sol.tmp ./src/test/addresses.sol
    forge build
    echo "# Creating initialization file for Echidna.."
    cp /tmp/echidna-init.json echidna-init.json
    echo "]" >> echidna-init.json # ensure JSON array ends validly
    # JSON from etheno has some values as numbers but Echidna expects all of them to be a string
    sed -i 's/"\([^"]\{1,32\}\)": \([0-9]\{1,32\}\)/"\1": "\2"/g' echidna-init.json
    echo "# WARNING: Keeping etheno/ganache instance running in the background for Forge fuzzing!"
    echo "# Stop it with 'kill -s SIGTERM $ETHENO_PID' when you're done!"
}


## ---------------------- MAKE CHANGES HERE ----------------------- ##

# Fetch implementations to fuzz
FETCH ./src/implementation/example/BytesLib.sol "https://raw.githubusercontent.com/GNSPS/solidity-bytes-utils/master/contracts/BytesLib.sol"
FETCH ./src/implementation/example/BytesUtil.sol "https://raw.githubusercontent.com/libertylocked/solidity-bytesutil/master/contracts/BytesUtil.sol"

# Compile contracts
BUILD

# Record deployment of contracts
RECORD_START

DEPLOY ./src/expose/example/BytesLib.sol ExposedBytesLib
DEPLOY ./src/expose/example/BytesUtil.sol ExposedBytesUtil

RECORD_END