#!/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)
#
# Process repos.yaml via gitaggregate and refresh addons/ symlinks.
# Run as the instance user (no sudo needed).

set -euo pipefail

BUILD_DIR="$(cd "$(dirname "$0")/.." && pwd)"
INSTANCE="$(basename "$(dirname "$BUILD_DIR")")"
GIT_CACHE="${HOME}/git"

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

# ---------------------------------------------------------------------------
# Git cache
# ---------------------------------------------------------------------------

# Compute local cache path for a git URL (without checking existence).
# Returns empty string if the URL can't be mapped to a cache path.
url_to_cache_path() {
    local url="$1" org repo
    case "$url" in
        git@*) url="${url#git@}"; url="${url/://}" ;;
    esac
    case "$url" in
        https://*) url="${url#https://}" ;;
        http://*)  url="${url#http://}" ;;
        ssh://*)   url="${url#ssh://}" ;;
    esac
    url="${url#*/}"
    url="${url%.git}"
    [[ "$url" != *"/"* ]] && return 0
    org="${url%%/*}"
    repo="${url#*/}"
    repo="${repo%%/*}"
    [[ -z "$org" || -z "$repo" ]] && return 0
    echo "${GIT_CACHE}/${org,,}/${repo,,}"
}

# Compute local cache path for a git URL.
# Returns empty string if the URL can't be mapped or no cache exists.
url_to_cache() {
    local cache
    cache=$(url_to_cache_path "$1") || return 0
    [[ -d "$cache" ]] && echo "$cache"
}

# Convert GitHub HTTPS URLs to SSH so fetches use the user's SSH keys
# instead of prompting for HTTPS credentials.
normalize_git_url() {
    local url="$1"
    if [[ "$url" == https://github.com/* ]]; then
        local path="${url#https://github.com/}"
        echo "git@github.com:${path}"
    else
        echo "$url"
    fi
}

# Clone a repo into the cache, or fetch if it already exists.
# Returns 0 on success (clone or fetch), 1 if clone failed.
clone_or_fetch() {
    local url="$1" cache="$2"
    local name="${cache#${GIT_CACHE}/}"
    local ssh_url
    ssh_url=$(normalize_git_url "$url")

    if [[ -d "${cache}/.git" ]]; then
        # Migrate old sat cache repos: the remote was renamed from 'origin'
        # to the repos.yaml name (e.g. 'oca').  Rename it back to 'origin' so
        # ensure_local_branch can use origin/<branch> consistently.
        if ! git -C "$cache" remote get-url origin &>/dev/null; then
            local first_remote
            first_remote=$(git -C "$cache" remote 2>/dev/null | head -1)
            if [[ -n "$first_remote" ]]; then
                git -C "$cache" remote rename "$first_remote" origin 2>/dev/null || true
            fi
        fi
        # Clean up stale remotes from old sat (e.g. therp, josuesp1620)
        # that were added as named remotes to a shared cache repo.
        local r
        for r in $(git -C "$cache" remote 2>/dev/null); do
            [[ "$r" == "origin" ]] && continue
            git -C "$cache" remote remove "$r" 2>/dev/null || true
        done
        # Update remote URL to SSH if it was HTTPS (migration)
        local current_url
        current_url=$(git -C "$cache" remote get-url origin 2>/dev/null || true)
        if [[ "$current_url" != "$ssh_url" ]]; then
            git -C "$cache" remote set-url origin "$ssh_url" 2>/dev/null || true
        fi
        info "  Fetching ${name}..."
        git -C "$cache" fetch origin --quiet 2>&1 \
            || warn "  Failed to fetch ${name} (using cached version)"
        return 0
    fi

    # Remove stale non-git directory
    [[ -d "$cache" ]] && rm -rf "$cache"
    mkdir -p "$(dirname "$cache")"
    info "  Cloning ${name} from ${ssh_url}..."
    if ! git clone "$ssh_url" "$cache" 2>&1; then
        warn "  Failed to clone ${ssh_url} (will use remote URL in repos.local.yaml)"
        return 1
    fi
    return 0
}

# Create a local branch from origin/<branch> if it doesn't already exist.
ensure_local_branch() {
    local cache="$1" branch="$2"
    git -C "$cache" show-ref --verify --quiet "refs/heads/${branch}" 2>/dev/null && return 0
    git -C "$cache" branch "$branch" "origin/${branch}" 2>/dev/null \
        || warn "  Failed to create local branch ${branch} in ${cache#${GIT_CACHE}/}"
}

# Populate the git cache from repos.yaml.  Each remote URL gets its own
# cache at ~/git/<org>/<repo>/.  Local branches are created for every
# merge target so gitaggregate can fetch them from the local cache.
# This ensures bin/build works standalone — without a prior
# `sat install odoo-dev` run to populate the cache.
populate_cache() {
    local src="${BUILD_DIR}/repos.yaml"
    [[ -f "$src" ]] || return 0

    info "Populating git cache from repos.yaml..."

    # Expand $ODOO_VERSION for parsing (the actual repos.yaml keeps the
    # placeholder for gitaggregate's --expand-env).
    local repos_expanded
    repos_expanded=$(sed "s/\$ODOO_VERSION/${VERSION}/g" "$src")

    # Parse repos.yaml with awk to extract structured records:
    #   REMOTE <part> <remote_name> <url>
    #   MERGE  <part> <remote_name> <branch>
    local records
    records=$(awk '
        /^[[:space:]]*#/ { next }
        /^[[:space:]]*$/ { next }
        /^[^[:space:]]/ {
            gsub(/:$/, "", $0)
            part = $0
            first_remote = ""
            next
        }
        /remotes:/ { in_remotes = 1; in_merges = 0; next }
        /merges:/ { in_remotes = 0; in_merges = 1; next }
        /^[[:space:]]+defaults:/ { in_remotes = 0; in_merges = 0; next }
        in_remotes && /[[:space:]]+[a-zA-Z0-9_-]+:/ {
            name = $1; sub(/:$/, "", name)
            url = $2; gsub(/[",]/, "", url)
            if (url ~ /^(https|http|ssh):\/\/|^git@/) {
                if (first_remote == "") {
                    first_remote = name
                }
                printf "REMOTE\t%s\t%s\t%s\n", part, name, url
            }
            next
        }
        in_merges && /[[:space:]]+-/ {
            line = $0; sub(/^[[:space:]]+-[[:space:]]*/, "", line)
            gsub(/[",]/, "", line)
            split(line, mparts, " ")
            if (length(mparts) >= 2) {
                printf "MERGE\t%s\t%s\t%s\n", part, mparts[1], mparts[2]
            } else if (length(mparts) == 1 && first_remote != "") {
                printf "MERGE\t%s\t%s\t%s\n", part, first_remote, mparts[1]
            }
            next
        }
    ' <<< "$repos_expanded")

    local TAB=$'\t'

    # Get unique parts in order of first appearance.
    local parts_order=""
    declare -A _seen=()
    while IFS=$'\t' read -r type part rname rval; do
        [[ -n "$part" ]] || continue
        if [[ -z "${_seen[$part]:-}" ]]; then
            _seen[$part]=1
            parts_order+="${part}"$'\n'
        fi
    done <<< "$records"

    # Process each part: clone/fetch each remote, then create local branches.
    while IFS= read -r part; do
        [[ -n "$part" ]] || continue

        local part_remotes part_merges
        part_remotes=$(grep "^REMOTE${TAB}${part}${TAB}" <<< "$records" | cut -f3,4 || true)
        part_merges=$(grep "^MERGE${TAB}${part}${TAB}" <<< "$records" | cut -f3,4 || true)
        [[ -n "$part_remotes" ]] || continue

        # Clone/fetch each remote into its own cache path
        local rname rurl cache
        while IFS=$'\t' read -r rname rurl; do
            [[ -n "$rurl" ]] || continue
            cache=$(url_to_cache_path "$rurl") || true
            [[ -n "$cache" ]] || continue
            clone_or_fetch "$rurl" "$cache" || true
        done <<< "$part_remotes"

        # Create local branches for merge targets
        local mname mbranch merge_url
        while IFS=$'\t' read -r mname mbranch; do
            [[ -n "$mbranch" ]] || continue
            # Find the URL for this remote name in this part
            merge_url=$(grep "^REMOTE${TAB}${part}${TAB}${mname}${TAB}" <<< "$records" | cut -f4 || true)
            [[ -n "$merge_url" ]] || continue
            cache=$(url_to_cache_path "$merge_url") || true
            [[ -n "$cache" ]] || continue
            [[ -d "${cache}/.git" ]] || continue
            ensure_local_branch "$cache" "$mbranch"
        done <<< "$part_merges"

    done <<< "$parts_order"

    info "Git cache ready."
}

# ---------------------------------------------------------------------------
# repos.local.yaml
# ---------------------------------------------------------------------------

# Regenerate repos.local.yaml from repos.yaml, replacing remote URLs with
# local cache paths where a cache exists.  Always regenerates to pick up
# newly cloned repos from populate_cache.
refresh_local_yml() {
    local src="${BUILD_DIR}/repos.yaml"
    local dst="${BUILD_DIR}/repos.local.yaml"
    [[ -f "$src" ]] || return 0

    info "Refreshing repos.local.yaml from repos.yaml..."
    cp "$src" "$dst"

    # Extract all remote URLs from repos.yaml and replace with local paths.
    local url cache
    while IFS= read -r url; do
        [[ -n "$url" ]] || continue
        cache=$(url_to_cache "$url") || true
        if [[ -n "$cache" ]]; then
            sed -i "s|${url}|${cache}|g" "$dst"
        fi
    done < <(grep -oE '(https?://[^ "'\''"]+|git@[^ "'\''"]+)' "$src" || true)

    # Touch dst to match src mtime so gitaggregate sees it as current.
    touch -r "$src" "$dst"
    info "repos.local.yaml refreshed."
}

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

# Detect Odoo version from the deploy-<version> branch name.
branch=$(git -C "$BUILD_DIR" rev-parse --abbrev-ref HEAD 2>/dev/null) \
    || error "Not a git repository: ${BUILD_DIR}"
[[ "$branch" == deploy-* ]] \
    || error "Unexpected branch '${branch}' — expected 'deploy-<version>'."
VERSION="${branch#deploy-}"

info "Instance: ${INSTANCE}  Version: ${VERSION}  Branch: ${branch}"

# Populate git cache from repos.yaml (clones new repos, fetches existing).
populate_cache

# Refresh repos.local.yaml from repos.yaml (regenerates if repos.yaml changed).
refresh_local_yml

# Prefer repos.local.yaml (local cache paths) if it exists; fall back to repos.yaml.
config="${BUILD_DIR}/repos.local.yaml"
[[ -f "$config" ]] || config="${BUILD_DIR}/repos.yaml"

# Run gitaggregate.
info "Running gitaggregate..."
env ODOO_VERSION="$VERSION" \
    bash -c "cd '${BUILD_DIR}' && '${BUILD_DIR}/.venv/bin/gitaggregate' \
        --expand-env \
        --config '${config}' \
        --jobs 4 \
        aggregate"
info "gitaggregate complete."

# Refresh addons symlinks.
info "Linking addons..."
bash "$(dirname "$0")/_link-addons"

info "Build complete."
