#!/usr/bin/env bash
# Copyright 2026 - Ronald Portier (Open Eye Development)
# SPDX-License-Identifier: AGPL-3.0-or-later  (https://www.gnu.org/licenses/agpl.html)
#
# Create/refresh symlinks in addons/ pointing at every Odoo module found in parts/.
# Supports optional whitelist and blacklist files in the build directory.
#
# Usage: bin/_link-addons
#
# whitelist / blacklist files (optional, live in <build-dir>):
#   One entry per line: <repo>/<module>, <repo>/*, or <repo>/<glob>
#   Repo name is the basename of the parts subdirectory (e.g. "web", "odoo", "custom").
#   Whitelist: if a repo is listed, only matching modules are linked; unlisted repos -> all modules.
#   Blacklist: overrides whitelist; 'base' can never be blacklisted.

set -euo pipefail

BUILD_DIR="$(cd "$(dirname "$0")/.." && pwd)"

PARTS_DIR="${BUILD_DIR}/parts"
ADDONS_DIR="${BUILD_DIR}/addons"
WHITELIST="${BUILD_DIR}/whitelist"
BLACKLIST="${BUILD_DIR}/blacklist"

info()  { echo "[INFO]  $*"; }
warn()  { echo "[WARN]  $*" >&2; }
error() { echo "[ERROR] $*" >&2; exit 1; }

# ---------------------------------------------------------------------------
# Parse whitelist and blacklist files into associative arrays.
# Keys = repo names; values = newline-separated glob patterns.
# ---------------------------------------------------------------------------

declare -A WL_REPOS=()
declare -A BL_REPOS=()

parse_list_file() {
    local file="$1" type="$2"
    local lineno=0 line repo pat
    while IFS= read -r line || [[ -n "$line" ]]; do
        lineno=$(( lineno + 1 ))
        line="${line%%#*}"
        line="${line#"${line%%[![:space:]]*}"}"
        line="${line%"${line##*[![:space:]]}"}"
        [[ -z "$line" ]] && continue
        if [[ "$line" != */* ]]; then
            warn "${type} line ${lineno}: expected '<repo>/<module>' — ignoring: ${line}"
            continue
        fi
        repo="${line%%/*}"
        pat="${line#*/}"
        if [[ "$type" == "whitelist" ]]; then
            WL_REPOS["$repo"]+="${pat}"$'\n'
        else
            BL_REPOS["$repo"]+="${pat}"$'\n'
        fi
    done < "$file"
}

[[ -f "$WHITELIST" ]] && parse_list_file "$WHITELIST" "whitelist"
[[ -f "$BLACKLIST" ]] && parse_list_file "$BLACKLIST" "blacklist"

# ---------------------------------------------------------------------------
# Determine whether a module should be symlinked.
# ---------------------------------------------------------------------------

should_link() {
    local repo="$1" module="$2"
    local pat matched

    # base is always linked; warn if blacklist tries to exclude it
    if [[ "$module" == "base" ]]; then
        if [[ -f "$BLACKLIST" ]] && [[ -v "BL_REPOS[$repo]" ]]; then
            while IFS= read -r pat; do
                [[ -z "$pat" ]] && continue
                # shellcheck disable=SC2053,SC2254
                if [[ "$module" == $pat ]]; then
                    warn "Ignoring blacklist entry '${repo}/${pat}': 'base' cannot be blacklisted."
                    break
                fi
            done <<< "${BL_REPOS[$repo]}"
        fi
        return 0
    fi

    # Whitelist: if the repo is mentioned, only include modules matching its patterns
    if [[ -f "$WHITELIST" ]] && [[ -v "WL_REPOS[$repo]" ]]; then
        matched=0
        while IFS= read -r pat; do
            [[ -z "$pat" ]] && continue
            # shellcheck disable=SC2053,SC2254
            [[ "$module" == $pat ]] && { matched=1; break; }
        done <<< "${WL_REPOS[$repo]}"
        [[ "$matched" -eq 0 ]] && return 1
    fi

    # Blacklist: exclude modules matching patterns
    if [[ -f "$BLACKLIST" ]] && [[ -v "BL_REPOS[$repo]" ]]; then
        while IFS= read -r pat; do
            [[ -z "$pat" ]] && continue
            # shellcheck disable=SC2053,SC2254
            [[ "$module" == $pat ]] && return 1
        done <<< "${BL_REPOS[$repo]}"
    fi

    return 0
}

# ---------------------------------------------------------------------------
# Prepare addons/ — clear stale symlinks
# ---------------------------------------------------------------------------

mkdir -p "$ADDONS_DIR"
find "$ADDONS_DIR" -maxdepth 1 -type l -delete

# ---------------------------------------------------------------------------
# Link modules from a scan directory into addons/
# repo: logical repo name used for whitelist/blacklist matching
# ---------------------------------------------------------------------------

total_linked=0

link_modules_from() {
    local repo="$1" scan_dir="$2"
    local linked=0 mod_dir mod_name existing

    [[ -d "$scan_dir" ]] || return 0

    while IFS= read -r mod_dir; do
        [[ -f "${mod_dir}/__manifest__.py" ]] || continue
        mod_name="$(basename "$mod_dir")"

        should_link "$repo" "$mod_name" || continue

        if [[ -L "${ADDONS_DIR}/${mod_name}" ]]; then
            existing="$(readlink "${ADDONS_DIR}/${mod_name}")"
            warn "Name collision: '${mod_name}' from ${mod_dir} overrides ${existing}"
        fi

        ln -sf "$mod_dir" "${ADDONS_DIR}/${mod_name}"
        linked=$(( linked + 1 ))
    done < <(find "$scan_dir" -maxdepth 1 -mindepth 1 -type d | sort)

    if [[ "$linked" -gt 0 ]]; then
        info "  ${linked} module(s) from ${repo} (${scan_dir##"${PARTS_DIR}/"})"
    fi
    total_linked=$(( total_linked + linked ))
}

# OCB (parts/odoo) — scan both addons directories; repo name "odoo"
link_modules_from "odoo" "${PARTS_DIR}/odoo/odoo/addons"
link_modules_from "odoo" "${PARTS_DIR}/odoo/addons"

# Org-prefixed repos at parts/<org>/<repo> (depth 2 under parts/)
link_all_org_repos() {
    local repo_dir repo_name parent
    while IFS= read -r repo_dir; do
        parent="$(dirname "$repo_dir")"
        # Skip subdirs of parts/odoo (OCB — handled above)
        [[ "$parent" == "${PARTS_DIR}/odoo" ]] && continue
        # Skip subdirs of parts/custom (handled separately below)
        [[ "$parent" == "${PARTS_DIR}/custom" ]] && continue
        repo_name="$(basename "$repo_dir")"
        link_modules_from "$repo_name" "$repo_dir"
    done < <(find "$PARTS_DIR" -maxdepth 2 -mindepth 2 -type d 2>/dev/null | sort)
}
link_all_org_repos

# Custom modules at parts/custom (depth 1, no org prefix); repo name "custom"
link_modules_from "custom" "${PARTS_DIR}/custom"

info "Total: ${total_linked} module(s) symlinked in ${ADDONS_DIR}."
