#cloud-config
autoinstall:
  version: 1
  locale: pt_BR.UTF-8
  keyboard:
    layout: br
  timezone: America/Fortaleza
  identity:
    hostname: nvr-appliance
    username: nvr-setup
    # Conta tecnica local para console fisico. SSH por senha permanece
    # desativado; a senha inicial e temporaria e deve ser trocada no primeiro
    # login local.
    password: "$6$2VvrtE8U/QylFvKv$PbOg6VKpuNETx7aYGoDxj9yWRZqNGcQj6EUJxw0CJiJRe/MLpfjc0GFdoA7cXCfOMVHBi5kI6uJKZ8OWosWlo0"
  ssh:
    install-server: true
    allow-pw: false
  early-commands:
    - |
      bash -eu <<'NVR_STORAGE_GUARD'
      LOG_FILE=/var/log/installer/nvr-storage-decision.log
      mkdir -p "$(dirname "$LOG_FILE")"
      exec > >(tee -a "$LOG_FILE") 2>&1

      log() {
        printf '[guarda-armazenamento-nvr] %s\n' "$*"
      }

      fail() {
        log "BLOQUEADO: $*"
        cat >/run/nvr-storage-blocked.txt <<EOF
      Instalacao NVR bloqueada antes do particionamento.

      Motivo: $*

      SSD/disco vazio e unico: a ISO segue automaticamente.
      Disco com particoes, Windows, Linux, assinaturas ou multiplos discos: reinicie
      com confirmacao explicita do operador.

      Confirmacao avancada por kernel cmdline:
        nvr_wipe_confirm=APAGAR nvr_install_disk=/dev/sdX
      ou, quando preparado pelo iniciador Windows:
        nvr_wipe_confirm=APAGAR nvr_install_disk_serial=SERIAL_DO_DISCO

      Nada foi formatado por esta etapa.
      EOF
        cat /run/nvr-storage-blocked.txt
        exit 1
      }

      cmdline_value() {
        name="$1"
        for word in $(cat /proc/cmdline); do
          case "$word" in
            "$name"=*) printf '%s\n' "${word#*=}"; return 0 ;;
          esac
        done
        return 1
      }

      config_value() {
        name="$1"
        file=/cdrom/nvr-appliance/wipe-confirm.conf
        [ -r "$file" ] || return 1
        sed -n "s/^${name}=//p" "$file" | tail -n 1
      }

      NVR_WIPE_CONFIRM="$(cmdline_value nvr_wipe_confirm || config_value NVR_WIPE_CONFIRM || true)"
      NVR_INSTALL_DISK="$(cmdline_value nvr_install_disk || config_value NVR_INSTALL_DISK || true)"
      NVR_INSTALL_DISK_SERIAL="$(cmdline_value nvr_install_disk_serial || config_value NVR_INSTALL_DISK_SERIAL || true)"
      NVR_BOOT_MODE="$(cmdline_value nvr_boot_mode || config_value NVR_BOOT_MODE || true)"
      case "$NVR_BOOT_MODE" in
        wipe|safe_wipe) : ;;
        *)
          if ! cmdline_value nvr_wipe_confirm >/dev/null 2>&1; then
            NVR_WIPE_CONFIRM=""
          fi
          ;;
      esac

      mapfile -t candidates < <(lsblk -dpno NAME,TYPE,RM,RO | awk '$2=="disk" && $3=="0" && $4=="0" {print $1}')
      [ "${#candidates[@]}" -gt 0 ] || fail "nenhum disco interno gravavel encontrado"

      log "discos candidatos detectados:"
      for disk in "${candidates[@]}"; do
        lsblk -dno NAME,SIZE,MODEL,SERIAL,TRAN "$disk" 2>/dev/null || printf '%s\n' "$disk"
      done

      log "validando origem NoCloud em /cdrom/autoinstall"
      cat /proc/cmdline | sed 's/^/[cmdline] /'
      findmnt /cdrom || true
      [ -r /cdrom/autoinstall/user-data ] || fail "arquivo /cdrom/autoinstall/user-data nao esta acessivel no boot"
      [ -r /cdrom/autoinstall/meta-data ] || fail "arquivo /cdrom/autoinstall/meta-data nao esta acessivel no boot"
      sha256sum /cdrom/autoinstall/user-data /cdrom/autoinstall/meta-data || true

      target=""
      if [ -n "$NVR_INSTALL_DISK" ]; then
        for disk in "${candidates[@]}"; do
          if [ "$disk" = "$NVR_INSTALL_DISK" ]; then
            target="$disk"
            break
          fi
        done
        [ -n "$target" ] || fail "nvr_install_disk informado nao corresponde a um disco interno gravavel: ${NVR_INSTALL_DISK}"
      elif [ -n "$NVR_INSTALL_DISK_SERIAL" ]; then
        for disk in "${candidates[@]}"; do
          disk_serial="$(lsblk -dn -o SERIAL "$disk" 2>/dev/null | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
          if [ "$disk_serial" = "$NVR_INSTALL_DISK_SERIAL" ]; then
            target="$disk"
            break
          fi
        done
        [ -n "$target" ] || fail "nvr_install_disk_serial informado nao foi encontrado nos discos internos: ${NVR_INSTALL_DISK_SERIAL}"
      elif [ "${#candidates[@]}" -eq 1 ]; then
        target="${candidates[0]}"
      else
        fail "multiplos discos internos detectados; selecione um disco com nvr_install_disk=/dev/... ou nvr_install_disk_serial=..."
      fi

      has_partitions=0
      if lsblk -nr "$target" -o TYPE | grep -qx part; then
        has_partitions=1
      fi

      has_signatures=0
      while IFS= read -r dev; do
        if wipefs -n "$dev" 2>/dev/null | awk 'NR > 1 {found=1} END {exit found ? 0 : 1}'; then
          has_signatures=1
        fi
      done < <(lsblk -lnp "$target" -o NAME)

      log "disco alvo=${target}; particoes=${has_partitions}; assinaturas=${has_signatures}; modo_boot=${NVR_BOOT_MODE:-<ausente>}; confirmacao=${NVR_WIPE_CONFIRM:-<ausente>}"

      if [ "$has_partitions" = "1" ] || [ "$has_signatures" = "1" ]; then
        log "orientacao: este disco contem particoes. Para apagar e instalar, use a opcao de instalacao destrutiva do menu ou confirme APAGAR com disco alvo explicito."
        [ "$NVR_WIPE_CONFIRM" = "APAGAR" ] || fail "disco alvo contem particoes/assinaturas; exige nvr_wipe_confirm=APAGAR"
        log "confirmacao destrutiva recebida para disco com dados; prosseguindo por decisao explicita"
      else
        log "disco alvo vazio; prosseguindo sem confirmacao destrutiva"
      fi

      grep -q '__NVR_INSTALL_DISK__' /autoinstall.yaml || fail "placeholder de disco nao encontrado em /autoinstall.yaml"
      sed_target="$(printf '%s' "$target" | sed 's/[#&]/\\&/g')"
      sed -i "s#__NVR_INSTALL_DISK__#${sed_target}#g" /autoinstall.yaml
      log "storage layout limitado ao disco alvo ${target}"
      NVR_STORAGE_GUARD
  # A instalacao do appliance evita baixar pacotes durante o autoinstall.
  # Pacotes do NVR sao instalados no primeiro boot pelo repositorio offline
  # embutido em /nvr-appliance/offline-apt.
  # Perfil appliance destrutivo/zero-touch: a VM/maquina de destino deve ser
  # dedicada ao NVR. SSH por senha permanece desabilitado; para homologacao,
  # injete uma chave publica na geracao da ISO com ISO_SSH_AUTHORIZED_KEY.
  storage:
    layout:
      name: direct
      match:
        path: __NVR_INSTALL_DISK__
  late-commands:
    - curtin in-target --target=/target -- mkdir -p /opt/nvr-appliance-installer /etc/nvr-appliance /var/log/nvr /var/lib/nvr
    - |
      bash -eu <<'NVR_NETWORK_TARGET'
      target=/target
      mkdir -p \
        "$target/etc/netplan" \
        "$target/etc/systemd/network" \
        "$target/etc/systemd/system/systemd-networkd-wait-online.service.d" \
        "$target/etc/NetworkManager/conf.d" \
        "$target/etc/NetworkManager/system-connections" \
        "$target/etc/issue.d" \
        "$target/etc/update-motd.d" \
        "$target/etc/nvr-appliance" \
        "$target/usr/local/sbin"

      cat > "$target/etc/netplan/01-nvr-wired-dhcp.yaml" <<'EOF'
      network:
        version: 2
        renderer: networkd
        ethernets:
          nvr-wired:
            match:
              name: "en*"
            dhcp4: true
            dhcp6: false
            optional: true
      EOF
      chmod 0600 "$target/etc/netplan/01-nvr-wired-dhcp.yaml"

      cat > "$target/etc/systemd/network/20-nvr-wired.network" <<'EOF'
      [Match]
      Name=en* eth*

      [Network]
      DHCP=yes
      IPv6AcceptRA=yes

      [DHCP]
      RouteMetric=100
      EOF
      chmod 0644 "$target/etc/systemd/network/20-nvr-wired.network"

      wait_bin=/usr/lib/systemd/systemd-networkd-wait-online
      [ -x "$target$wait_bin" ] || wait_bin=/lib/systemd/systemd-networkd-wait-online
      cat > "$target/etc/systemd/system/systemd-networkd-wait-online.service.d/10-nvr-timeout.conf" <<EOF
      [Service]
      ExecStart=
      ExecStart=${wait_bin} --any --timeout=20
      EOF
      chmod 0644 "$target/etc/systemd/system/systemd-networkd-wait-online.service.d/10-nvr-timeout.conf"

      cat > "$target/etc/NetworkManager/conf.d/10-nvr-preserve-wired.conf" <<'EOF'
      [keyfile]
      unmanaged-devices=interface-name:en*;interface-name:eth*
      EOF
      chmod 0644 "$target/etc/NetworkManager/conf.d/10-nvr-preserve-wired.conf"

      cat > "$target/etc/issue.d/90-nvr-appliance.issue" <<'EOF'
      Appliance NVR instalado.

      Usuário técnico local: nvr-setup
      Senha inicial temporária: Nvr-Setup-2026!
      Troque a senha no primeiro login local.

      A primeira ativação do serial exige internet.
      Se a rede não estiver funcionando, verifique o cabo ou configure pelo console.
      EOF
      chmod 0644 "$target/etc/issue.d/90-nvr-appliance.issue"

      cat > "$target/etc/update-motd.d/90-nvr-appliance" <<'EOF'
      #!/bin/sh
      ip="$(hostname -I 2>/dev/null | awk '{print $1}')"
      ip="${ip:-127.0.0.1}"
      echo "Appliance NVR instalado."
      echo
      echo "Acesse o NVR pelo navegador:"
      echo "  http://${ip}/nvr/"
      echo
      echo "O endereço http://${ip}/ redireciona automaticamente para o NVR local."
      echo "A primeira ativação exige internet."
      echo "Se a rede não estiver funcionando, verifique o cabo ou configure a rede pelo console."
      echo
      echo "Usuário técnico local: nvr-setup"
      echo "Comandos úteis:"
      echo "  sudo nvr-status-local"
      echo "  sudo nvr-wifi-configure"
      echo "  curl -fsSL https://simplavende.com.br/suporte/liberar-e-corrigir-nvr.sh -o /tmp/liberar-e-corrigir-nvr.sh"
      echo "  sudo NVR_SUPPORT_AUTHORIZED_KEY='ssh-ed25519 ...' bash /tmp/liberar-e-corrigir-nvr.sh"
      echo "  sudo journalctl -u nvr-first-boot-install.service --no-pager"
      EOF
      chmod 0755 "$target/etc/update-motd.d/90-nvr-appliance"

      cat > "$target/usr/local/sbin/nvr-status-local" <<'EOF'
      #!/usr/bin/env bash
      set -u
      ip="$(hostname -I 2>/dev/null | awk '{print $1}')"
      ip="${ip:-127.0.0.1}"
      echo "Status local do Appliance NVR"
      echo "IP detectado: ${ip}"
      echo "URL NVR: http://${ip}/nvr/"
      echo "Raiz local: http://${ip}/ redireciona para o NVR."
      echo
      echo "Interfaces de rede:"
      ip -br link || true
      ip -br addr || true
      echo
      echo "Wi-Fi:"
      if command -v nvr-wifi-configure >/dev/null 2>&1; then
        nvr-wifi-configure --status || true
      else
        echo "nvr-wifi-configure ausente"
      fi
      echo
      echo "Teste de internet:"
      if timeout 12 ping -c 4 8.8.8.8 >/dev/null 2>&1; then
        echo "Internet: ok"
      else
        echo "Internet: não detectada. Verifique o cabo. A ativação do serial exigirá internet."
      fi
      echo
      echo "Servicos NVR:"
      systemctl --no-pager --plain status nvr-stack.target gateway-daemon gateway-local-web platform-queue 2>/dev/null || true
      EOF
      chmod 0755 "$target/usr/local/sbin/nvr-status-local"
      NVR_NETWORK_TARGET
    - curtin in-target --target=/target -- systemctl enable systemd-networkd.service systemd-resolved.service || true
    - curtin in-target --target=/target -- ln -sf ../run/systemd/resolve/stub-resolv.conf /etc/resolv.conf || true
    - curtin in-target --target=/target -- usermod -s /bin/bash nvr-setup
    - printf '%s\n' 'nvr-setup:Nvr-Setup-2026!' | curtin in-target --target=/target -- chpasswd
    - curtin in-target --target=/target -- passwd -e nvr-setup
    - printf '%s\n' 'nvr-setup ALL=(ALL) ALL' > /target/etc/sudoers.d/90-nvr-setup-local-console
    - curtin in-target --target=/target -- chown root:root /etc/sudoers.d/90-nvr-setup-local-console
    - curtin in-target --target=/target -- chmod 0440 /etc/sudoers.d/90-nvr-setup-local-console
    - cp /var/log/installer/nvr-storage-decision.log /target/var/log/nvr/storage-decision.log || true
    - cp /var/log/installer/nvr-storage-decision.log /target/var/log/nvr/autoinstall-source.log || true
    - curtin in-target --target=/target -- chown root:root /var/log/nvr/storage-decision.log || true
    - curtin in-target --target=/target -- chmod 0600 /var/log/nvr/storage-decision.log || true
    - curtin in-target --target=/target -- chown root:root /var/log/nvr/autoinstall-source.log || true
    - curtin in-target --target=/target -- chmod 0600 /var/log/nvr/autoinstall-source.log || true
    - cp -a /cdrom/nvr-appliance/. /target/opt/nvr-appliance-installer/
    - |
      bash -eu <<'NVR_APT_OFFLINE'
      if [ -s /target/opt/nvr-appliance-installer/offline-apt/Packages.gz ]; then
        mkdir -p /target/etc/apt/sources.list.d /target/etc/apt/sources.list.d.disabled-by-nvr /target/etc/apt
        if [ -f /target/etc/apt/sources.list ]; then
          mv /target/etc/apt/sources.list /target/etc/apt/sources.list.disabled-by-nvr
        fi
        find /target/etc/apt/sources.list.d -maxdepth 1 -type f \( -name '*.list' -o -name '*.sources' \) -exec mv {} /target/etc/apt/sources.list.d.disabled-by-nvr/ \; || true
        cat > /target/etc/apt/sources.list.d/nvr-offline.list <<'EOF'
      deb [trusted=yes] file:/opt/nvr-appliance-installer/offline-apt ./
      EOF
      fi
      NVR_APT_OFFLINE
    - cp /cdrom/nvr-appliance/nvr-appliance.env.example /target/etc/nvr-appliance/nvr-appliance.env
    - curtin in-target --target=/target -- chown root:root /etc/nvr-appliance/nvr-appliance.env
    - curtin in-target --target=/target -- chmod 0600 /etc/nvr-appliance/nvr-appliance.env
    - cp /cdrom/nvr-appliance/nvr-first-boot-install.service /target/etc/systemd/system/nvr-first-boot-install.service
    - curtin in-target --target=/target -- chown root:root /etc/systemd/system/nvr-first-boot-install.service
    - curtin in-target --target=/target -- chmod 0644 /etc/systemd/system/nvr-first-boot-install.service
    - cp /cdrom/nvr-appliance/nvr-wifi-configure.sh /target/usr/local/sbin/nvr-wifi-configure
    - curtin in-target --target=/target -- chown root:root /usr/local/sbin/nvr-wifi-configure
    - curtin in-target --target=/target -- chmod 0755 /usr/local/sbin/nvr-wifi-configure
    - cp /cdrom/nvr-appliance/nvr-appliance-control.sh /target/usr/local/sbin/nvr-appliance-control
    - curtin in-target --target=/target -- chown root:root /usr/local/sbin/nvr-appliance-control
    - curtin in-target --target=/target -- chmod 0755 /usr/local/sbin/nvr-appliance-control
    - cp /cdrom/nvr-appliance/nvr-support-unlock.sh /target/usr/local/sbin/nvr-support-unlock
    - curtin in-target --target=/target -- chown root:root /usr/local/sbin/nvr-support-unlock
    - curtin in-target --target=/target -- chmod 0755 /usr/local/sbin/nvr-support-unlock
    - cp /cdrom/nvr-appliance/nvr-console-panel.sh /target/usr/local/sbin/nvr-console-panel
    - curtin in-target --target=/target -- chown root:root /usr/local/sbin/nvr-console-panel
    - curtin in-target --target=/target -- chmod 0755 /usr/local/sbin/nvr-console-panel
    - cp /cdrom/nvr-appliance/nvr-console-panel.service /target/etc/systemd/system/nvr-console-panel.service
    - sed -i 's#__INSTALL_ROOT__#/opt/nvr#g' /target/etc/systemd/system/nvr-console-panel.service
    - curtin in-target --target=/target -- chown root:root /etc/systemd/system/nvr-console-panel.service
    - curtin in-target --target=/target -- chmod 0644 /etc/systemd/system/nvr-console-panel.service
    - curtin in-target --target=/target -- chmod 0755 /opt/nvr-appliance-installer/first-boot-nvr-install.sh
    - if [ -f /cdrom/nvr-appliance/authorized_keys ]; then curtin in-target --target=/target -- mkdir -p /home/nvr-setup/.ssh; cp /cdrom/nvr-appliance/authorized_keys /target/home/nvr-setup/.ssh/authorized_keys; curtin in-target --target=/target -- chown -R nvr-setup:nvr-setup /home/nvr-setup/.ssh; curtin in-target --target=/target -- chmod 0700 /home/nvr-setup/.ssh; curtin in-target --target=/target -- chmod 0600 /home/nvr-setup/.ssh/authorized_keys; printf '%s\n' 'nvr-setup ALL=(ALL) NOPASSWD:ALL' > /target/etc/sudoers.d/90-nvr-setup-ssh-key; curtin in-target --target=/target -- chown root:root /etc/sudoers.d/90-nvr-setup-ssh-key; curtin in-target --target=/target -- chmod 0440 /etc/sudoers.d/90-nvr-setup-ssh-key; fi
    - curtin in-target --target=/target -- systemctl enable getty@tty2.service
    - curtin in-target --target=/target -- systemctl disable getty@tty1.service || true
    - curtin in-target --target=/target -- systemctl enable nvr-console-panel.service
    - curtin in-target --target=/target -- systemctl enable nvr-first-boot-install.service
