#!/bin/bash
# Agent config copy and PVC persistence utilities for the paude entrypoint.
# Sourced by entrypoint-session.sh — not run standalone.

# Copy agent config from a source directory into $HOME.
# Handles: recursive copy, config file relocation, plugin permissions, OpenShift ownership.
# Skips runtime directories/files that are generated by the agent inside the
# container — these may be persisted on PVC and must not be overwritten by
# (stale or empty) host-side copies. This is defense-in-depth: the host-side
# rsync already excludes these, but we guard here too.
# Args: source_path (directory containing agent config files)
copy_agent_config() {
    local source_path="$1"
    local dest="$HOME/$AGENT_CONFIG_DIR"

    mkdir -p "$dest"
    chmod g+rwX "$dest" 2>/dev/null || true

    # Copy items individually, skipping runtime state that the agent generates
    # inside the container. Keep in sync with _CLAUDE_CONFIG_EXCLUDES in
    # src/paude/agents/claude.py — this is defense-in-depth (host-side rsync
    # already excludes these).
    for item in "$source_path"/* "$source_path"/.*; do
        [[ ! -e "$item" ]] && continue
        local name
        name="${item##*/}"
        case "$name" in
            .|..) continue ;;
            backups|cache|debug|downloads|file-history|paste-cache|plans|\
            session-env|sessions|shell-snapshots|statsig|tasks|todos|projects|.git)
                [[ -d "$item" ]] && continue ;;
            history.jsonl|stats-cache.json)
                [[ -f "$item" ]] && continue ;;
        esac
        cp -dR --preserve=mode,timestamps "$item" "$dest/" 2>/dev/null || true
    done

    # Handle config file specially - goes to ~/.<config_file>
    # Use cp instead of mv to write through symlinks (on re-execution,
    # persist_agent_config may have already symlinked paths to /pvc).
    if [[ -n "$AGENT_CONFIG_FILE" ]] && [[ -n "$AGENT_CONFIG_FILE_BASENAME" ]] && [[ -f "$HOME/$AGENT_CONFIG_DIR/$AGENT_CONFIG_FILE_BASENAME" ]]; then
        cp -f "$HOME/$AGENT_CONFIG_DIR/$AGENT_CONFIG_FILE_BASENAME" "$HOME/$AGENT_CONFIG_FILE" 2>/dev/null || true
        rm -f "$HOME/$AGENT_CONFIG_DIR/$AGENT_CONFIG_FILE_BASENAME" 2>/dev/null || true
        chmod g+rw "$HOME/$AGENT_CONFIG_FILE" 2>/dev/null || true
    fi

    # g+rwX sets read/write and execute on directories (X = execute only if dir)
    # This covers plugins/ and all other subdirectories in one pass
    chmod -R g+rwX "$HOME/$AGENT_CONFIG_DIR" 2>/dev/null || true
}

# Persist agent config on the PVC volume so it survives container recreation.
# Creates symlinks: $HOME/$AGENT_CONFIG_DIR -> /pvc/$AGENT_CONFIG_DIR
#                    $HOME/$AGENT_CONFIG_FILE -> /pvc/$AGENT_CONFIG_FILE
# Follows the same pattern as agent binary persistence at /pvc/.local/bin.
persist_agent_config() {
    # Skip if /pvc doesn't exist (non-persistent setup)
    if [[ ! -d /pvc ]]; then
        return 0
    fi

    local pvc_config_dir="/pvc/$AGENT_CONFIG_DIR"
    local home_config_dir="$HOME/$AGENT_CONFIG_DIR"

    # Create PVC directory if it doesn't exist (first start)
    mkdir -p "$pvc_config_dir" 2>/dev/null || true
    chmod g+rwX "$pvc_config_dir" 2>/dev/null || true
    # Fix SELinux context on PVC config dir — earlier versions of cp -a
    # preserved the image filesystem context, making the dir inaccessible.
    chcon -R --reference=/pvc "$pvc_config_dir" 2>/dev/null || true

    # If HOME config dir is a real directory (not symlink), merge into PVC and replace with symlink
    if [[ ! -L "$home_config_dir" ]]; then
        if [[ -d "$home_config_dir" ]]; then
            cp -dR --preserve=mode,timestamps "$home_config_dir/." "$pvc_config_dir/" 2>/dev/null || true
        fi
        rm -rf "$home_config_dir" 2>/dev/null || true
        ln -sf "$pvc_config_dir" "$home_config_dir"
    fi

    # Config file (e.g., .claude.json) — symlink to PVC
    if [[ -n "$AGENT_CONFIG_FILE" ]]; then
        local pvc_config_file="/pvc/$AGENT_CONFIG_FILE"
        local home_config_file="$HOME/$AGENT_CONFIG_FILE"

        # If HOME config file is a real file (not symlink), move to PVC
        if [[ -f "$home_config_file" ]] && [[ ! -L "$home_config_file" ]]; then
            if [[ ! -f "$pvc_config_file" ]]; then
                cp -dR --preserve=mode,timestamps "$home_config_file" "$pvc_config_file" 2>/dev/null || true
            fi
            rm -f "$home_config_file"
        fi

        # Create PVC file if it doesn't exist
        if [[ ! -f "$pvc_config_file" ]]; then
            echo '{}' > "$pvc_config_file" 2>/dev/null || true
        fi
        chmod g+rw "$pvc_config_file" 2>/dev/null || true
        chcon --reference=/pvc "$pvc_config_file" 2>/dev/null || true

        # Create symlink
        if [[ ! -L "$home_config_file" ]]; then
            rm -f "$home_config_file" 2>/dev/null || true
            ln -sf "$pvc_config_file" "$home_config_file"
        fi
    fi
}
