#!/bin/bash
#args=("$@")
args=()
while [[ $# -gt 0 ]]; do
  case $1 in
    -h|--help)
      cat $HOME/.sumake/help.txt
      args+=("$1")
      exit 0
      ;;
    --make-help)
      make -h
      exit 0
      ;;
    -v|--version)
      echo "sumake: 0.2.6"
      args+=("$1")
      ;;
    --zsh-init)
append_content=$(cat <<EOF
# sumake zsh completion
autoload -U compinit
compinit
_sumake() {
_make "\$@"
}
compdef _sumake sumake
zstyle ':completion::complete:sumake:*:targets' call-command true
EOF
)
if ! grep -q "# sumake zsh completion" ~/.zshrc ; then
  echo "$append_content" >> ~/.zshrc
  echo "zsh completion init done"
else
  echo "zsh completion already init"
fi

      exit 0
      ;;
    *)
      args+=("$1")
      ;;
  esac
  shift
done

export SUMAKE="$(which sumake)"
cmd="make"
utils_mk="/Users/peng/.sumake/utils.mk"
if [ ! -f $utils_mk ]; then
  utils_mk="$HOME/.sumake/utils.mk"
fi
cmd+=" -f $utils_mk"
if [ -f Makefile ]; then
  cmd+=" -f Makefile "
fi
echo [sumake] $cmd "${args[@]}"

env_file=""
if [ -f "$PWD/.env.make" ]; then
  echo "Including .env.make file"
  env_file="$PWD/.env.make"
elif [ -f "$PWD/.env" ]; then
  echo "Including .env file"
  env_file="$PWD/.env"
fi

echo "env_file: $env_file"
if [ -n "$env_file" ]; then
  source $env_file && $cmd "${args[@]}"
else
  $cmd "${args[@]}"
fi
