#!/bin/bash

set -e

dir=tests/behaviour
SOLC_VERSION="0.8.14"

#check if first argument --version=xxxx is passed and set SOLC_VERSION to it
if [ -z "$VERSION" ]; then
    echo -e "\033[33mWARNING:\033[0m No solc version specified for semantic tests, using default version \033[0;32m$SOLC_VERSION\033[0m"
else 
    SOLC_VERSION="$VERSION"
    echo "Using solc version $SOLC_VERSION"
fi

SOLC_URL="https://github.com/ethereum/solidity/releases/download/v${SOLC_VERSION}/solidity_${SOLC_VERSION}.tar.gz"

#check if URL is valid
if ! curl --output /dev/null --silent --head --fail "$SOLC_URL"; then
    echo -e "\033[31mERROR:\033[0m: Invalid version specified:  \033[0;32m$SOLC_VERSION\033[0m"
    exit 1
fi

if [[ ! -d $dir/solidity/ ]]; then
  mkdir -p $dir/solidity
fi

pushd $dir/solidity > /dev/null
  # Empty current directory
  rm -rf ./*
  if [[ ! -f solidity_${SOLC_VERSION}.tar.gz ]]; then
    curl -LJO $SOLC_URL
  fi
  tar -xf  solidity_${SOLC_VERSION}.tar.gz --strip-components=1 "solidity_${SOLC_VERSION}/test/libsolidity/semanticTests/"
  rm -rf solidity_${SOLC_VERSION}.tar.gz
popd > /dev/null

######### TODO get a version of isoltest for each platform and generate
######## testCalldata.ts instead of having it checked in
# Generate calldata
case "$(uname -s)" in
  Darwin*)
    isoltest=$dir/bin/darwin/isoltest
    ;;
  Linux*)
    isoltest=$dir/bin/linux/isoltest
    ;;
esac

# Typescript was not resolving the type of the calldata json
# generated by isoltest nore was it enjoying the empty stub
# that was used as a placeholder. This way ts properly understands
# the type of the data.
cat > $dir/testCalldata.ts <<- EOM
import { ITestCalldata } from './expectations/semantic';

const tests : {[file: string]: ITestCalldata[] | null} =
EOM
$isoltest --print-test-expectations \
  --testpath $dir/solidity/test/libsolidity/semanticTests/ \
  >> $dir/testCalldata.ts
cat >> $dir/testCalldata.ts <<- EOM
export default tests;
EOM

