#!/usr/bin/env bash

set -e

ROOT_DOMAIN_NAME="infra-root"
OWNER="platform-team"

echo "Generating Backstage catalog files..."

#
# 1. Create root catalog-info.yaml
#
ROOT_FILE="catalog-info.yaml"

if [[ -f "$ROOT_FILE" ]]; then
  echo "Root catalog-info.yaml already exists — skipping"
else
  echo "Creating root catalog-info.yaml"
  cat > "$ROOT_FILE" <<EOF
apiVersion: backstage.io/v1alpha1
kind: Domain
metadata:
  name: ${ROOT_DOMAIN_NAME}
  title: Infrastructure Root
spec:
  owner: ${OWNER}
EOF
fi

#
# Add children: top-level directories
#
TOP_LEVEL_DIRS=()
while IFS= read -r -d '' dir; do
    TOP_LEVEL_DIRS+=("$dir")
done < <(find . -mindepth 1 -maxdepth 1 -type d -print0)

echo "Adding children to root catalog-info.yaml"
echo "  children:" >> "$ROOT_FILE"
for d in "${TOP_LEVEL_DIRS[@]}"; do
  name=$(basename "$d")
  echo "    - ./${name}/catalog-info.yaml" >> "$ROOT_FILE"
done


#
# 2. Process each top-level directory as a System
#
for dir in "${TOP_LEVEL_DIRS[@]}"; do
  SYS_NAME=$(basename "$dir")
  SYS_FILE="${dir}/catalog-info.yaml"

  if [[ -f "$SYS_FILE" ]]; then
    echo "System file already exists for $SYS_NAME — skipping"
  else
    echo "Creating system catalog-info.yaml for $SYS_NAME"
    cat > "$SYS_FILE" <<EOF
apiVersion: backstage.io/v1alpha1
kind: System
metadata:
  name: ${SYS_NAME}
  title: ${SYS_NAME^} System
spec:
  owner: ${OWNER}
  partOf:
    - ../catalog-info.yaml
  subcomponents:
EOF
  fi

  #
  # Append subcomponents for the system
  #
  SUBDIRS=()
  while IFS= read -r -d '' sub; do
      SUBDIRS+=("$sub")
  done < <(find "$dir" -mindepth 1 -maxdepth 1 -type d -print0)

  echo "  Adding components under $SYS_NAME"
  for s in "${SUBDIRS[@]}"; do
    SUB_NAME=$(basename "$s")
    echo "    - ./${SUB_NAME}/catalog-info.yaml" >> "$SYS_FILE"
  done


  #
  # 3. Create component files in subdirectories
  #
  for s in "${SUBDIRS[@]}"; do
    SUB_NAME=$(basename "$s")
    COMPONENT_FILE="${s}/catalog-info.yaml"

    if [[ -f "$COMPONENT_FILE" ]]; then
      echo "Component file exists for $SYS_NAME/$SUB_NAME — skipping"
    else
      echo "Creating component file: $SYS_NAME/$SUB_NAME"
      cat > "$COMPONENT_FILE" <<EOF
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
  name: ${SYS_NAME}-${SUB_NAME}
  title: ${SUB_NAME^} (${SYS_NAME})
spec:
  type: service
  lifecycle: production
  owner: ${OWNER}
  partOf:
    - ../catalog-info.yaml
EOF
    fi

  done

done

echo "Done! All catalog-info.yaml files are created."
