#!/bin/sh

HEADER_KEY="THIS HEADER IS AUTOGENERATED. DO NOT MODIFY MANUALLY."
HEADER="
/**
* $HEADER_KEY
* ! For any changes, please update the '/openvidu-meet/typings' directory.
**/"
SOURCE_DIR="src"

FRONTEND_DIR="../frontend/projects/shared-meet-components/src/lib/typings/ce"
BACKEND_DIR="../backend/src/typings/ce"
TYPES_DIR="../../openvidu-meet-pro/types/src/ce"

add_headers() {
  find "$SOURCE_DIR" -type f -name "*.ts" | while IFS= read -r file; do
    if ! grep -qF "$HEADER_KEY" "$file"; then
      printf "%s\n\n%s" "$HEADER" "$(cat "$file")" >"${file}.tmp" && mv "${file}.tmp" "$file"
    fi
  done
}

copy_files_with_headers() {
  TARGET_DIR="$1"
  mkdir -p "$TARGET_DIR"

  find "$SOURCE_DIR" -type f -name "*.ts" | while IFS= read -r file; do
    RELATIVE_PATH="${file#$SOURCE_DIR/}"
    DEST_FILE="$TARGET_DIR/$RELATIVE_PATH"

    mkdir -p "$(dirname "$DEST_FILE")"

    printf "%s\n\n%s" "$HEADER" "$(cat "$file")" >"$DEST_FILE"
  done
}

if [ "$1" = "ce" ]; then
  TARGET_DIRS="$FRONTEND_DIR $BACKEND_DIR"
elif [ "$1" = "pro" ]; then
  TARGET_DIRS="$TYPES_DIR"
else
  echo "No argument provided. Copying to both CE and PRO"
  TARGET_DIRS="$FRONTEND_DIR $BACKEND_DIR $TYPES_DIR"
fi

echo "Copying files to target directories..."
for TARGET_DIR in $TARGET_DIRS; do
  copy_files_with_headers "$TARGET_DIR"
done

echo "Types have been synced successfully."
