#!/usr/bin/env bash # apply.sh # Añade la automatización al config.yaml del agente . # Usa yq si está disponible; en caso contrario imprime el bloque YAML para copiar a mano. set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" if [[ $# -ne 2 ]]; then echo "Uso: $0 " >&2 echo "Ejemplo: $0 good-morning assistant-bot" >&2 exit 1 fi NAME="$1" AGENT_ID="$2" SCHEDULE_FILE="$REPO_ROOT/crons/$NAME/schedule.yaml" AGENT_CONFIG="$REPO_ROOT/agents/$AGENT_ID/config.yaml" if [[ ! -f "$SCHEDULE_FILE" ]]; then echo "Error: no existe crons/$NAME/schedule.yaml" >&2 echo "Usa ./dev-scripts/cron/list.sh para ver las automatizaciones disponibles." >&2 exit 1 fi if [[ ! -f "$AGENT_CONFIG" ]]; then echo "Error: no existe agents/$AGENT_ID/config.yaml" >&2 exit 1 fi # Parse schedule.yaml fields kind="" template="" cron_expr="" while IFS= read -r line; do case "$line" in " kind:"*) kind="${line#*kind:}"; kind="${kind// /}" ;; " template:"*) template="${line#*template:}"; template="${template# }" ;; default_cron:*) cron_expr="${line#default_cron:}"; cron_expr="${cron_expr# }"; cron_expr="${cron_expr//\"/}" ;; esac done < "$SCHEDULE_FILE" if [[ -z "$kind" || -z "$template" || -z "$cron_expr" ]]; then echo "Error: schedule.yaml incompleto (falta kind, template o default_cron)." >&2 exit 1 fi # Build YAML block YAML_BLOCK=" - name: $NAME cron: \"$cron_expr\" output_room: \"\" # TODO: reemplaza con la sala real del agente action: kind: $kind template: \"$template\"" # Try yq first if command -v yq &>/dev/null; then # Check if schedules key already has this entry existing=$(yq ".schedules // [] | .[] | select(.name == \"$NAME\") | .name" "$AGENT_CONFIG" 2>/dev/null || true) if [[ -n "$existing" ]]; then echo "Advertencia: el agente $AGENT_ID ya tiene un schedule llamado '$NAME'. No se añade de nuevo." exit 0 fi # Append using yq yq -i ".schedules += [{\"name\": \"$NAME\", \"cron\": \"$cron_expr\", \"output_room\": \"\", \"action\": {\"kind\": \"$kind\", \"template\": \"$template\"}}]" "$AGENT_CONFIG" echo "✓ Añadido schedule '$NAME' a agents/$AGENT_ID/config.yaml" echo "→ Edita output_room en agents/$AGENT_ID/config.yaml para apuntar a la sala correcta." else echo "yq no está disponible. Añade manualmente el siguiente bloque a agents/$AGENT_ID/config.yaml:" echo "" echo "schedules:" echo "$YAML_BLOCK" echo "" echo "→ Edita output_room para apuntar a la sala correcta del agente." fi