#cloud-config
# Minimal user-data: download bootstrap.sh from your file server and run it at first boot.
#
# 1. Host bootstrap.sh at a URL reachable from the device on first boot (e.g. your
#    provisioning portal or file server). Example: http://10.20.50.1:5000/files/bootstrap.sh
# 2. Copy this file to the boot partition as "user-data" (with meta-data and optional network-config).
# 3. Edit BOOTSTRAP_URL below to match your server (or set it once in the runcmd section).
#
# DNS: Use NetworkManager rc-manager=symlink so /etc/resolv.conf gets DHCP DNS (LXC option 6).
# RPi OS does not use systemd-resolved by default. Ensure bootstrap.sh does not overwrite
# /etc/resolv.conf. See docs/DEVICE-DNS-DHCP-RESOLVCONF.md.

package_update: true
package_upgrade: false

# Keep /etc/hosts in sync with hostname (from meta-data or set below)
manage_etc_hosts: true

# Do not overwrite /etc/resolv.conf; NetworkManager will manage it with DHCP DNS
manage_resolv_conf: false

packages:
  - curl

# Ensure SSH is enabled and password auth allowed so you can log in after first boot
write_files:
  - path: /etc/ssh/sshd_config.d/99-cloud-init.conf
    content: |
      PasswordAuthentication yes
      PermitRootLogin no

  # NetworkManager: manage resolv.conf via symlink so it gets DNS from DHCP (option 6 from LXC).
  # RPi OS does not use systemd-resolved; NM writes /etc/resolv.conf -> /run/NetworkManager/resolv.conf.
  - path: /etc/NetworkManager/conf.d/99-resolv-dhcp.conf
    content: |
      [main]
      rc-manager=symlink
    permissions: '0644'

runcmd:
  # Remove static resolv.conf so NM creates its symlink with DHCP DNS (file.server will resolve).
  - rm -f /etc/resolv.conf
  - systemctl restart NetworkManager || true
  - systemctl enable ssh
  - systemctl start ssh
  # Download and run bootstrap script (edit URL to match your file server)
  - |
    BOOTSTRAP_URL="http://file.server:5000/files/bootstrap.sh"
    LOG="/var/log/cloud-init-bootstrap.log"
    if ! curl -fsSL "$BOOTSTRAP_URL" -o /tmp/bootstrap.sh 2>>"$LOG" || [ ! -s /tmp/bootstrap.sh ]; then
      echo "$(date -Iseconds) ERROR: Failed to download bootstrap.sh from $BOOTSTRAP_URL (file missing or empty)" >> "$LOG"
      exit 0
    fi
    chmod +x /tmp/bootstrap.sh
    /tmp/bootstrap.sh
  - cloud-init single --name cc_final_message
