#!/bin/bash

# Deploys peer-shell (the forced-command dispatcher) to a stable path under
# the manager user's home so authorized_keys can point at it. Idempotent —
# safe to call on every peer pairing. Also writes ~/.libreportal-env so
# peer-shell can find containers_dir without bootstrapping the full repo.

_peerShellPath() { echo "${HOME}/.local/bin/peer-shell"; }
_peerShellSrc()  { echo "${install_scripts_dir}peer/peer_shell.sh"; }
_peerEnvPath()   { echo "${HOME}/.libreportal-env"; }

peerInstallShell()
{
    local dest src env
    dest=$(_peerShellPath)
    src=$(_peerShellSrc)
    env=$(_peerEnvPath)

    if [[ ! -f "$src" ]]; then
        isError "peer-shell source missing at $src"
        return 1
    fi

    mkdir -p "$(dirname "$dest")"

    # Copy + chmod. Compare first so we don't rewrite on every call.
    if [[ ! -f "$dest" ]] || ! cmp -s "$src" "$dest"; then
        cp "$src" "$dest"
        chmod 700 "$dest"
        isSuccessful "Installed peer-shell to $dest"
    fi

    # Write the env file peer-shell sources. Just enough for it to locate the
    # container tree. We re-emit on every call because containers_dir may
    # change with a relocation.
    {
        printf '# Auto-written by peerInstallShell — do not edit.\n'
        printf 'containers_dir=%q\n' "${containers_dir:-/libreportal-containers/}"
    } > "$env"
    chmod 600 "$env"
}
