# NOTE: This script is intended for use by external repos that depend
#   on the Dharma smart contracts in any capacity. If a developer wants
#   to deploy the Dharma smart contracts in their local blockchain environment,
#   they can call this script, which will deploy the Dharma smart contracts
#   to their local chain and subsequently *locally* update the artifacts exported by
#   the package to reflect the newly deployed contracts' addresses.
#
# We use the build/ directory as a day-to-day development
# environment, and use the artifacts/ directory to store production
# artifacts (i.e. artifacts which we publish in the @dharmaprotocol/contracts
# NPM package).
#
# Truffle will by default use the build folder to fetch the most recent
# artifacts and update them with the newly deployed contract
# addresses, saving the newest artifacts in build.
#
# Thus, when pushing a new build to a development network, we want to replace build
# folder with most recent saved  production artifacts/ directory contents
# so that our new artifacts include the addresses of contracts deployed in production
# on networks *other* than development.
rm build/contracts/*
cp artifacts/json/* build/contracts/

# Re-compile all contracts
truffle compile --all

# Deploy contracts onto development network
truffle migrate --reset --network development

# Replace production artifacts with newly generated json artifacts
rm artifacts/json/*
cp build/contracts/* artifacts/json/

# Remove old transpiled artifacts from the artifacts/ directory
rm artifacts/ts/*

# Transform raw JSON artifacts into Typescript modules.  This makes
# interacting with the artifacts significantly easier when exporting
# them as modules.
for filename in build/contracts/*.json; do
    filename_base=$(basename $filename .json)
    echo -e "export const $filename_base = " > "artifacts/ts/$filename_base.ts"
    cat "build/contracts/$filename_base.json" >> "artifacts/ts/$filename_base.ts"

    echo -e "Transpiled $filename_base.json into $filename_base.ts"
done

echo -e "Successfully deployed contracts onto Development Testnet!"
