#!/bin/bash

die() {
    printf "ERROR: %s\n" "$*"
    exit 1
}

dieOnError() {
    if [ $? -ne 0 ]; then
        die $1
    fi
}

NETWORK=${NETWORK:-localhost}

POOL=`npx hardhat --network $NETWORK deploy $VERIFY \
    --currency-address 0xf8acfb5d9a57216974819f8b2da74e1fb18902cc \
    --nft-name "Ensuro Policies NFT" --nft-symbol "EPOL" \
    --treasury-address 0x20Ce2e29ca6a7Ca6820D6DD3959A4761EE000091 |
    egrep -o  "^PolicyPool deployed to: (https?://.*/)?0x[0-9a-fA-F]+" |
    sed -r 's|PolicyPool deployed to: (https?://.*/)?(0x[0-9a-fA-F]+)|\2|g'`

if [ $? -ne 0 ]; then
    die "Error deploying pool"
fi

echo "PolicyPool = $POOL"

npx hardhat --network $NETWORK deploy:eToken $VERIFY --pool-address $POOL \
    --etk-symbol eUSD1MONTH --etk-name "eToken USD 1month" --expiration-period 30

npx hardhat --network $NETWORK deploy:eToken $VERIFY --pool-address $POOL \
    --etk-symbol eUSD1YEAR --etk-name "eToken USD 1year" --expiration-period 365

npx hardhat --network $NETWORK deploy:fdRiskModule $VERIFY --pool-address $POOL \
    --rm-name "Flight Delay Insurance" --max-scr-per-policy 10000 --scr-limit 240000 \
    --scr-interest-rate 0.06 \
    --wallet 0xc62c56f50FcE8881Ec5D7271Af5Bea6f18c88183 \
    --link-token 0x326c977e6efc84e512bb9c30f76e30c160ed06fb \
    --oracle 0x0a908660e9319413a16978fa48df641b4bf37c54 \
    --data-job-id 0x2fb0c3a36f924e4ab43040291e14e0b7 \
    --sleep-job-id 0x4241bd0288324bf8a2c683833d0b824f
dieOnError "Error deploying Flight Delay Insurance RM"

npx hardhat --network $NETWORK deploy:riskModule $VERIFY --pool-address $POOL \
    --rm-name "Trustfull Insurance" --max-scr-per-policy 10000 --scr-limit 30000 \
    --scr-percentage 0.2 \
    --ensuro-fee 0.03 \
    --scr-interest-rate 0.1 \
    --wallet 0xc62c56f50FcE8881Ec5D7271Af5Bea6f18c88183
dieOnError "Error deploying Trustfull RM"

# FixedRateAssetManager
npx hardhat --network $NETWORK deploy:fixedInterestAssetManager $VERIFY \
    --pool-address $POOL \
    --interest-rate 0.2
dieOnError "Error deploying FixedRateAssetManager"
