#!/usr/bin/env bash
# Aplica los roles con el sistema real ya arrancado. Si algo falla no escribe
# el marcador y systemd lo vuelve a intentar en el siguiente arranque.
set -euo pipefail

MARKER=/var/lib/filmos/configured
PLAYBOOK=/usr/lib/filmos/ansible/site.yml
INVENTORY=/run/filmos-firstboot.inventory.ini
VARS=/run/filmos-firstboot.vars.json
MARKER_TEMP=""

marker_is_valid() {
  [ -s "$MARKER" ] \
    && grep -Eq '^configurado=.+$' "$MARKER" \
    && grep -Eq '^usuario=.+$' "$MARKER"
}

cleanup_marker_temp() {
  [ -z "$MARKER_TEMP" ] || rm -f -- "$MARKER_TEMP"
}
trap cleanup_marker_temp EXIT

if marker_is_valid; then
  systemctl disable filmos-firstboot.service >/dev/null
  exit 0
fi
[ -f "$PLAYBOOK" ] || { echo "No existe $PLAYBOOK" >&2; exit 1; }

uid_min="$(awk '$1 == "UID_MIN" {print $2; exit}' /etc/login.defs)"
uid_min="${uid_min:-1000}"
mapfile -t users < <(
  getent passwd | awk -F: -v min="$uid_min" \
    '$3 >= min && $3 < 60000 && $6 ~ /^\/home\// && $7 !~ /(nologin|false)$/ {print $1}'
)

if [ "${#users[@]}" -ne 1 ]; then
  printf 'Esperaba un usuario humano y encontré %s: %s\n' \
    "${#users[@]}" "${users[*]:-ninguno}" >&2
  exit 1
fi

filmos_user="${users[0]}"
filmos_group="$(id -gn "$filmos_user")"

printf '[filmos]\nlocalhost ansible_connection=local ansible_python_interpreter=/usr/bin/python3\n' \
  > "$INVENTORY"
python3 - "$VARS" "$filmos_user" "$filmos_group" <<'PY'
import json
import sys

path, user, group = sys.argv[1:]
with open(path, "w") as handle:
    json.dump({"filmos_user": user, "filmos_group": group}, handle)
PY

cd /usr/lib/filmos/ansible
ansible-playbook -i "$INVENTORY" "$PLAYBOOK" -e "@$VARS"

install -d -m 0755 /var/lib/filmos
MARKER_TEMP="$(mktemp /var/lib/filmos/.configured.XXXXXX)"
printf 'configurado=%s\nusuario=%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$filmos_user" \
  > "$MARKER_TEMP"
chmod 0644 "$MARKER_TEMP"
sync -f "$MARKER_TEMP" 2>/dev/null || sync
mv -f -- "$MARKER_TEMP" "$MARKER"
sync -f "$(dirname -- "$MARKER")" 2>/dev/null || sync
MARKER_TEMP=""
systemctl disable filmos-firstboot.service >/dev/null
