#!/bin/bash

set -euo pipefail

THISDIR=$(dirname $0)
EPICS_ROOT="${EPICS_ROOT:-/epics}"

# ibek resolves entity models from $EPICS_ROOT/ibek-defs, never from
# ibek-support*/ directly, so collect the support yaml from both submodules here.
shopt -s nullglob
defs=("$THISDIR"/ibek-support*/*/*.ibek.support.yaml)
shopt -u nullglob

if [ ${#defs[@]} -eq 0 ]; then
    echo "ERROR: no *.ibek.support.yaml found under $THISDIR/ibek-support*/" >&2
    echo "       are the submodules initialised? git submodule update --init" >&2
    exit 1
fi

# A support folder that is present but empty yields a partial ibek-defs, whose
# symptom is a handful of entities failing rather than an obvious error. Say so.
shopt -s nullglob
for support in "$THISDIR"/ibek-support*/; do
    contributed=("${support}"*/*.ibek.support.yaml)
    if [ ${#contributed[@]} -eq 0 ]; then
        echo "WARNING: ${support} holds no *.ibek.support.yaml;" \
             "entities from it will be missing" >&2
    fi
done
shopt -u nullglob

# ibek-defs is flat, so two support yaml sharing a basename collide there and
# only one survives.
#
# Byte-identical copies are legal: a module may be forked (a DLS build of an
# upstream module, say) so that the two folders differ only in install.yml, and
# any one generic IOC pulls in exactly one of them. The entity models are the
# same either way, so the schema does not depend on who wins - link the first
# and skip the rest.
#
# Differing content is the hazard, and what `ln` does about it varies by
# coreutils version: it may silently let the last one win (leaving a schema
# quietly missing whatever the loser defined), or refuse with "will not
# overwrite just-created", which names the files but not the problem. Neither
# is a good way to find out, so check first and say exactly what clashed.
declare -A first_seen=()
unique_defs=()
conflicts=()
for def in "${defs[@]}"; do
    base=${def##*/}
    first=${first_seen[$base]:-}
    if [ -z "${first}" ]; then
        first_seen[$base]=$def
        unique_defs+=("$def")
    elif cmp -s "${first}" "${def}"; then
        echo "NOTE: ${base} is duplicated with identical content;" \
             "linking ${first}, ignoring ${def}" >&2
    else
        conflicts+=("$base")
    fi
done

if [ ${#conflicts[@]} -gt 0 ]; then
    echo "ERROR: support yaml sharing a basename but differing in content" \
         "would collide in $EPICS_ROOT/ibek-defs/:" >&2
    while IFS= read -r base; do
        echo "  ${base}" >&2
        for def in "${defs[@]}"; do
            [ "${def##*/}" = "${base}" ] && echo "      ${def}" >&2
        done
    done < <(printf '%s\n' "${conflicts[@]}" | sort -u)
    echo "       remove or rename all but one of each; a module may live in" \
         "more than one ibek-support* folder only if its support yaml is" \
         "identical in each" >&2
    exit 1
fi

# Each support module lives in exactly one folder across the ibek-support*
# submodules. Two folders declaring the same `module:` (compared ignoring case,
# as asyn and ASYN would otherwise slip past) give two definitions of the
# same entity types, and which one a generic IOC gets depends on which folder
# its Dockerfile copies. The one exception is a fork: the same support yaml,
# byte for byte, with a different install.yml (ether_ip / ether_ip_dls).
#
# Known pending duplicates, each a pair of folders that may share a module name
# until the duplicate is resolved. Keep this list short and give every entry a
# reason; it is not a way to add new duplicates.
# Each entry is "folderA folderB", the two folders relative to the repo root
# and sorted in C (byte) order, e.g. "ibek-support-dls/foo ibek-support/foo".
module_clash_allowlist=(
)

declare -A module_first_def=()
module_clashes=()
for def in "${defs[@]}"; do
    module=$(sed -n -E 's/^module:[[:space:]]*["'\'']?([^"'\''#[:space:]]+).*/\1/p' \
        "${def}" | head -n 1)
    if [ -z "${module}" ]; then
        echo "ERROR: ${def} declares no top-level module:" >&2
        exit 1
    fi
    key=${module,,}
    first=${module_first_def[$key]:-}
    if [ -z "${first}" ]; then
        module_first_def[$key]=$def
        continue
    fi
    first_folder=$(dirname "${first}")
    folder=$(dirname "${def}")
    if [ "${first_folder}" = "${folder}" ] || cmp -s "${first}" "${def}"; then
        continue
    fi
    pair=$(printf '%s\n' "${first_folder#"$THISDIR"/}" "${folder#"$THISDIR"/}" \
        | LC_ALL=C sort | tr '\n' ' ')
    allowed=false
    for entry in "${module_clash_allowlist[@]}"; do
        [ "${entry} " = "${pair}" ] && allowed=true
    done
    if ${allowed}; then
        echo "NOTE: module ${module} is declared in both ${first_folder} and" \
             "${folder}; allowed as a known pending duplicate" >&2
    else
        module_clashes+=("module ${module}: ${first_folder} and ${folder}")
    fi
done

if [ ${#module_clashes[@]} -gt 0 ]; then
    echo "ERROR: support folders declaring the same module: (ignoring case)" \
         "with differing *.ibek.support.yaml:" >&2
    printf '  %s\n' "${module_clashes[@]}" >&2
    echo "       each module lives in exactly one folder across ibek-support*;" \
         "a fork may appear twice only if its support yaml is byte-identical" >&2
    exit 1
fi

# set up the generic IOC-like environment for ibek
mkdir -p "$EPICS_ROOT/ibek-defs/"
rm -f "$EPICS_ROOT"/ibek-defs/*
ln -srf "${unique_defs[@]}" "$EPICS_ROOT/ibek-defs/"

# generate into a temp file first so a failure leaves no truncated schema behind.
# It is a dotfile, which the rm above does not glob, so clean it up on the way out.
tmp_schema="$EPICS_ROOT/ibek-defs/.ioc.schema.json.tmp"
trap 'rm -f "${tmp_schema}"' EXIT
ibek ioc generate-schema > "${tmp_schema}"
mv "${tmp_schema}" "$EPICS_ROOT/ibek-defs/ioc.schema.json"
