#!/usr/bin/env bash
# Generate additional bindings for solidity contracts, not generated by abigen

DIR=${DIR:-./bindings}
PKG=${PKG:-bindings}

# generate bindings for the given contract
# works on contract name of fully qualified path to the contract
# params:
#  $1: contract name (ex. 'IPTokenStaking', 'src/protocol/IPTokenStaking.sol:IPTokenStaking')
gen_binding() {
  contract=$1

  # strip path prefix, if used
  # ex src/protocol/IPTokenStaking.sol:IPTokenStaking => IPTokenStaking
  name=$(echo "${contract}" | cut -d ":" -f 2)

  # convert to lower case to respect golang package naming conventions
  name_lower=$(echo "${name}" | tr '[:upper:]' '[:lower:]')


  # gen storage layout json
  storage_layout_file=${DIR}/${name_lower}_storage_layout.json
  forge inspect "${contract}" storageLayout --json > "${storage_layout_file}"

  # abigen does not generate the deployedBytecode, so we add it manually to {name_lower}_more.go

  deployed_bytecode=$(forge inspect ${contract} deployedBytecode --libraries "src/libraries/Secp256k1.sol:Secp256k1:0x00000000000000000000000000000000000256f1")
  file=${DIR}/${name_lower}_more.go

  cat <<EOF > "${file}"
package ${PKG}

import (
    _ "embed"
)

const (
    ${name}DeployedBytecode = "${deployed_bytecode}"
)

//go:embed ${name_lower}_storage_layout.json
var ${name_lower}StorageLayoutJSON []byte

var ${name}StorageLayout = mustGetStorageLayout(${name_lower}StorageLayoutJSON)
EOF

  # gofmt expects 600 permissions
  chmod 600 "${file}"
}


for contract in "$@"; do
  gen_binding "${contract}"
done
