#!/usr/bin/env bash

library_name=$1
library_directory=$2
target_name=$3
child_path=$4
include_path=$5
target_type=$6

children=$(find "$library_directory/src$child_path" -mindepth 1 -maxdepth 1 -type d | sort)
source_files=$(find "$library_directory/src$child_path" -maxdepth 1  -name "*.cpp" -or -name "*.cc" -or -name "*.h" -or -name "*.hpp" | sort)

if [[  $target_type == "library" ]]; then
  include_files=$(find "$library_directory/include/${include_path}${child_path}" -maxdepth 1 -name "*.h" -or -name "*.hpp" | sort)
fi

libname_underscore=${library_name//\//_}
sublib_underscore=${child_path//\//_}

echo "# THIS FILE HAS BEEN GENERATED BY THE BUILD CONFIGURATION SYSTEM - DO NOT EDIT"
echo ""

if (( "${#include_files}" > 0 )); then
  echo "set(MINECPP_${libname_underscore^^}${sublib_underscore^^}_INCLUDE_DIR \${MINECPP_${libname_underscore^^}_DIR}/include/$include_path$child_path)"
fi

if (( "${#include_files}" > 0 || "${#source_files}" > 0 )); then
  echo "target_sources($target_name"
  if (( "${#source_files}" > 0 ));  then
    echo "    # Source files"
    echo "    PRIVATE"
    for source_file in $source_files; do
    echo "        \${CMAKE_CURRENT_SOURCE_DIR}/$(basename $source_file)"
    done
  fi

  if (( "${#include_files}" > 0 ));  then
    echo ""
    echo "    # Header files"
    echo "    PUBLIC"
    for include_file in $include_files; do
    echo "        \${MINECPP_${libname_underscore^^}${sublib_underscore^^}_INCLUDE_DIR}/$(basename $include_file)"
    done
  fi
  echo ")"
  echo ""
fi

if (( ${#children} > 0 )); then

  echo "# Subdirectories"
  for subsublib in $children; do
      echo "add_subdirectory(\"$(basename $subsublib)\")"
  done
  echo ""

  for subsublib in $children; do
      ./meta/cmake-generate-source.sh "$library_name" "$library_directory" "$target_name" "${child_path}/$(basename $subsublib)" $include_path > "$library_directory/src${child_path}/$(basename $subsublib)/CMakeLists.txt" "$target_type"
  done

fi
