#!/bin/bash

generate_index() {
  for path in "$@"; do
    local base=$(basename "${path}")
    local exac=${base%.ts}
    local dir=$(dirname "${path}")

    local segments
    local p

    IFS="/" read -a segments <<< $path

    for segment in ${segments[@]}; do

      if [ "$segment" == "." ] || [ "$segment" == "clients" ]; then
        p+="$segment"
        p+="/"
        continue
      fi

      local exp

      if [ "$segment" == "$base" ]; then
        exp="export * from './$exac'"
        if grep -Fxq "$exp" "$dir"/index.ts; then
          echo "$exp" "-> current expression-string already exist in index.ts"
        else
          echo "$exp" | tee -a "$dir"/index.ts
        fi
        p=""
      elif [ "$segment" == "$exac" ]; then
        exp="export * as $segment from './$segment'"
        if grep -Fxq "$exp" "$p"/index.ts; then
          echo "$exp" "-> current expression-string already exist in index.ts"
        else
          echo "$exp" | tee -a "$p"/index.ts
        fi
        p+="$segment"
        p+="/"
      else
        exp="export * as $segment from './$segment'"
        if grep -Fxq "$exp" "$p"index.ts; then
          echo "$exp" "-> current expression-string already exist in index.ts"
        else
          echo "$exp" | tee -a "$p"index.ts
        fi
        p+="$segment"
        p+="/"
      fi

    done
  done
}

echo "---deleting existing *.d.ts, *.d.ts.map, *.js, *.js.map files"
find ./clients/*/**/ -path '*.d.ts' -delete
find ./clients/*/**/ -path '*.d.ts.map' -delete
find ./clients/*/**/ -path '*.js' -delete
find ./clients/*/**/ -path '*.js.map' -delete
find ./clients/*/**/ -path '*.ts.bak' -delete
find ./clients -path '*.d.ts' -delete
find ./clients -path '*.d.ts.map' -delete
find ./clients -path '*.js' -delete
find ./clients -path '*.js.map' -delete
find ./clients -path '*.ts.bak' -delete

echo "---generating index.ts files"
ts_files=$(find ./clients/**/ -name '*.ts')
ts_files_array=($ts_files)
generate_index "${ts_files_array[@]}"

echo "---generating *.d.ts, *.d.ts.map, *.js, *.js.map files"
npm i protobufjs@6.11.3
tsc --project ./config --declaration --declarationMap --sourceMap --rootDir ./clients

echo "---deleting created tmp files"
npm uninstall protobufjs@6.11.3
find ./clients -name 'index.ts' -delete
find ./clients/*/** -name 'index.ts' -delete
find ./ -maxdepth 1 -name '*.json' -delete

echo "---process finished"