#!/usr/bin/env bash
# Run after installing the signed yoriai-agent package.
set -euo pipefail
[[ $EUID == 0 ]] || { echo 'Run with sudo.' >&2; exit 1; }
recover=0
manage_ollama=0
bundle_file=''
while [[ $# -gt 0 ]]; do
    case "$1" in
        --recover) recover=1; shift ;;
        --manage-ollama) manage_ollama=1; shift ;;
        --bundle) [[ $# -ge 2 ]] || { echo '--bundle needs a file path' >&2; exit 2; }; bundle_file=$2; shift 2 ;;
        *) echo 'Usage: sudo yoriai-agent-join [--bundle FILE] [--recover] [--manage-ollama]' >&2; exit 2 ;;
    esac
done
if [[ $manage_ollama == 1 ]]; then
    systemctl cat ollama.service >/dev/null || { echo 'Install Ollama first; managed configuration requires an existing ollama.service.' >&2; exit 1; }
    dropin=/etc/systemd/system/ollama.service.d/50-yoriai.conf
    install -d -m 0755 /etc/systemd/system/ollama.service.d
    if [[ -f "$dropin" ]]; then cp -p "$dropin" "$dropin.backup.$(date +%s)"; fi
    echo 'Applying the packaged Ollama loopback/capacity settings and restarting ollama.service:'
    cat /usr/share/doc/yoriai-agent/ollama-yoriai-dropin.conf
    install -m 0644 /usr/share/doc/yoriai-agent/ollama-yoriai-dropin.conf "$dropin"
    systemctl daemon-reload
    systemctl restart ollama.service
fi
if [[ $recover == 1 && ( -f /var/lib/yoriai/agent/credentials.json || -f /var/lib/yoriai/agent/identity.json ) ]]; then
    systemctl stop yoriai-agent.service
    archive="/var/lib/yoriai/agent-recovery-$(date +%s)-$$"
    mv /var/lib/yoriai/agent "$archive"
    printf 'Previous identity retained in %s. A worker-specific recovery bundle is required.\n' "$archive"
fi
install -d -o yoriai-agent -g yoriai-agent -m 0700 /var/lib/yoriai/agent
install -d -m 0755 /etc/yoriai
if [[ ! -f /etc/yoriai/agent.toml ]]; then
    install -o yoriai-agent -g yoriai-agent -m 0640 /usr/share/doc/yoriai-agent/agent.toml.example /etc/yoriai/agent.toml
fi
chown yoriai-agent:yoriai-agent /etc/yoriai/agent.toml
/usr/bin/yoriai-ollama-inspect || echo 'Ollama settings could not be observed; capacity remains unknown until the agent can inspect ollama.service.' >&2
if [[ -f /var/lib/yoriai/agent/identity.json ]]; then
    if [[ -n "$bundle_file" ]]; then
        runuser -u yoriai-agent -- /usr/bin/yoriai-agent join --bundle - < "$bundle_file"
    fi
    echo 'Existing identity retained.'
else
    if [[ -n "$bundle_file" ]]; then
        runuser -u yoriai-agent -- /usr/bin/yoriai-agent join --bundle - < "$bundle_file"
    elif [[ -t 0 ]]; then
        read -r -s -p 'Paste the join bundle from Add worker, then press Enter: ' bundle
        echo
        printf '%s' "$bundle" | runuser -u yoriai-agent -- /usr/bin/yoriai-agent join --bundle -
        unset bundle
    else
        runuser -u yoriai-agent -- /usr/bin/yoriai-agent join --bundle -
    fi
fi
systemctl enable --now yoriai-agent.service
systemctl is-active --quiet yoriai-agent.service
printf 'Agent service started. Check worker readiness in the controller UI.\n'
