#!/bin/bash

CURR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)
DRIVER_DOCS="$CURR/../../adm/dist/fluffos/docs"       # update to driver path
LIB_DOCS="$CURR/../../doc/driver"        # update to mudlib path

types=("apply" "efun")    # exclude concepts, driver, stdlib, and zh-CN

for type in ${types[@]} ; do
  mkdir -p ${LIB_DOCS}/${type} # ensure mudlib dir exists

  for dir in ${DRIVER_DOCS}/${type}/*/ ; do
    dir=${dir%*/}           # remove trailing /

    for file in ${dir}/*.md ; do
      filename=${file##*/}    # grab everything after last /

      [[ ${filename} =~ ^__ ]] && continue        # ignore __INIT
      [[ ${filename} =~ ^README ]] && continue    # ignore README
      [[ ${filename} == index.md ]] && continue   # ignore index

      # new doc file path
      newDoc=${LIB_DOCS}/${type}/${filename%.md}
      echo "Processing ${newDoc}"

      cp ${file} ${newDoc}                        # copy file
      sed -i '1,5 d' ${newDoc}                    # trim frontmatter
      sed -i '/^#\s+${filename}\s*$/d' ${newDoc}  # remove title
      sed -i '/```\(c\|\)\s*$/d' ${newDoc}        # remove C code block tags
    done
  done
done
