#!/usr/bin/env bash

RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'

if [ -z "${BASH_VERSINFO}" ] || [ -z "${BASH_VERSINFO[0]}" ] || [ ${BASH_VERSINFO[0]} -lt 4 ]; then 
  echo "This script requires Bash version >= 4"; exit 1; 
fi

declare -A tools=()
declare -A desired=()

for arg in "$@"; do
  case ${arg%%=*} in
    "--with-go")
      desired[go]="${arg##*=}"
      ;;
    "--help")
      printf "${GREEN}$0${NC}\n"
      printf "  available options:\n"
      printf "  --with-go=${BLUE}<path_to_go_binary>${NC}\n"
      exit 0
      ;;
    *)
      echo "Unknown option: $arg"
      exit 2
      ;;
    esac
done

vercomp () {
    if [[ $1 == $2 ]]
    then
        return 0
    fi
    local IFS=.
    local i ver1=($1) ver2=($2)
    # fill empty fields in ver1 with zeros
    for ((i=${#ver1[@]}; i<${#ver2[@]}; i++))
    do
        ver1[i]=0
    done
    for ((i=0; i<${#ver1[@]}; i++))
    do
        if [[ -z ${ver2[i]} ]]
        then
            # fill empty fields in ver2 with zeros
            ver2[i]=0
        fi
        if ((10#${ver1[i]} > 10#${ver2[i]}))
        then
            return 1
        fi
        if ((10#${ver1[i]} < 10#${ver2[i]}))
        then
            return 2
        fi
    done
    return 0
}

check_for() {
  echo -n "Checking for $1... "
  if ! [ -z "${desired[$1]}" ]; then
    TOOL_PATH="${desired[$1]}"
  else
    TOOL_PATH=$(command -v $1)
  fi
  if ! [ -x "$TOOL_PATH" -a -f "$TOOL_PATH" ]; then
    printf "${RED}not found${NC}\n"
    cd -
    exit 1
  else
    printf "${GREEN}found${NC}\n"
    tools[$1]=$TOOL_PATH
  fi
}

check_go_version() {
  echo -n "Checking go version... "
  GO_VERSION=$(${tools[go]} version | ${tools[awk]} '{where = match($0, /[0-9]\.[0-9]+\.[0-9]*/); if (where != 0) print substr($0, RSTART, RLENGTH)}')
  vercomp $GO_VERSION 1.12
  case $? in
    0) ;&
    1)
      printf "${GREEN}"
      echo $GO_VERSION
      printf "${NC}"
      ;;
    2)
      printf "${RED}"
      echo "$GO_VERSION < 1.12"
      exit 1
      ;;
  esac
  VERSION=$(${tools[go]} version | ${tools[awk]} '{print $3}')
  tools["go_version"]="${VERSION}"
}

check_docker_version() {
  echo -n "Checking docker version... "
  DOCKER_VERSION=$(${tools[docker]} version | ${tools[awk]})
}

check_go_env() {
  echo -n "Checking \$GOPATH... "
  GOPATH="$(go env GOPATH)"
  if [ -z "$GOPATH" ]; then
    printf "${RED}invalid${NC} - GOPATH not set\n"
    exit 1
  fi
  printf "${GREEN}valid${NC} - $GOPATH\n"
}

cd ${0%/*}

rm -fv .env

check_for make
check_for awk
check_for go
check_go_version
check_go_env
check_for golangci-lint

echo

cat <<- EOF > .env
	MAKE := "${tools[make]}"
  GO := "${tools[go]}"
  GO_VERSION := ${tools[go_version]}
  GOLANGCILINT := "${tools[golangci-lint]}"
EOF

echo "Environment configuration written to .env"

cd - > /dev/null