#!/usr/bin/env bash

set -euo pipefail

project_name="driving"

function usage() {
    cat <<EOF
Creates a project for QtCreator with all the files from the repo.

Options:
    --name=NAME     Uses NAME as the project's name (default=driving).
    --fresh, -f     Generates a fresh project. The default is to only modify
                    the list of includes and the list of files and to not touch
                    the other files (.creator, .creator.user, .config)
EOF
}

for i in "$@"
do
case $i in
    --name=*)
    project_name="${i#*=}"
    shift
    ;;
    --fresh|-f)
    fresh="yes"
    shift
    ;;
    --help|-h)
    usage
    exit 0
    ;;
    *)
    # unknown option
    usage
    exit 1
    ;;
esac
done

script_directory="$( (builtin cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) )"
project_root="$( ( builtin cd "$script_directory" && git rev-parse --show-toplevel) )"

keep_files() {
  while read l
  do
    if [ -f $l ]
    then
      echo $l
    fi
  done
}

(
  builtin cd "$project_root"

  # Create the ".config" and ".creator" files.
  if [ ! -f "$project_name.config" ] || [ -v fresh ]
  then
    cat > "$project_name.config" <<EOF
// ADD PREDEFINED MACROS HERE!
#define __cplusplus 201103L
#define CUDA_FOUND
#define USE_OPENCV
EOF
  fi

  if [ ! -f "$project_name.creator" ] || [ -v fresh ]
  then
    echo "[General]" > "$project_name.creator"
  fi

  if [ ! -f "$project_name.creator.user" ] || [ -v fresh ]
  then
    # Create the ".creator.user" file from the template
    sed "s!PROJECT_ROOT_DIR!$project_root!g" "$script_directory/template.creator.user" > "$project_name.creator.user"
  fi

  # Create the ".files" file from bazel query
  # The query returns some "targets" so I am keeping only the actual files
  # (see https://groups.google.com/forum/#!topic/bazel-discuss/g713eXBFvd4)
  sources_query='labels(srcs, kind("cc_.* rule", ... + experimental/...)) + '\
'labels(hdrs, kind("cc_.* rule", ... + experimental/...)) + '\
'labels(src, kind("genproto rule", ... + experimental/...))'

  # bazel query with --keep_going will keep going but still report an error code
  # if it encouters errors. So disabling the error options temporarily :(
  set +euo pipefail
  bazel query --keep_going $sources_query | sed 's!^//!!g' | sed 's!:!/!g' | keep_files > "$project_name.files"
  set -euo pipefail

  # Create the ".includes" file.
  # This should be a bazel query, but somehow bazel query is buggy:
  # https://github.com/bazelbuild/bazel/issues/825
  # Therefore, I add manually a few paths, and find our includes by parsing
  # our list of files.
  "$script_directory/get_includes.py" "$project_name.files" > "$project_name.includes"
)
