#!/usr/bin/env bash
set -euo pipefail

# ... (existing variables/args) ...
BRAND="${IDH_BRAND:-}"
HOSTNAME_NEW="${IDH_HOSTNAME:-}"
DOC_URL="${IDH_DOC_URL:-}"
PORTAL_URL="${IDH_PORTAL_URL:-}"
SUPPORT_EMAIL="${IDH_SUPPORT_EMAIL:-}"
BRAND_COLOR="${IDH_COLOR:-}"
ENSURE_TIMER="on"   # <— NEW: daily ensure-timer default

# parse args
if [[ "${1:-}" == "--" ]]; then shift; fi
while [[ $# -gt 0 ]]; do
  case "$1" in
    --brand) BRAND="$2"; shift 2;;
    --hostname) HOSTNAME_NEW="$2"; shift 2;;
    --doc) DOC_URL="$2"; shift 2;;
    --portal) PORTAL_URL="$2"; shift 2;;
    --support) SUPPORT_EMAIL="$2"; shift 2;;
    --color) BRAND_COLOR="$2"; shift 2;;
    --ensure-timer) ENSURE_TIMER="${2,,}"; shift 2;;  # <— NEW: on/off
    --yes|-y) NONINTERACTIVE=1; shift;;
    *) echo "Unknown arg: $1" >&2; exit 1;;
  esac
done

# ... (existing os detection, helpers, pkg funcs) ...

BACKUP_DIR="/opt/idh-whitelabel/backup"
INSTALL_DIR="/opt/idh-whitelabel"
mkdir -p "$BACKUP_DIR" "$INSTALL_DIR"

# ... (existing interactive prompts and defaults) ...

# ... (existing color mapping) ...

disable_vendor_motd() {
  if [[ -d /etc/update-motd.d ]]; then
    chmod -x /etc/update-motd.d/* 2>/dev/null || true
  fi
  if [[ -f /etc/default/motd-news ]]; then
    sed -i 's/^ENABLED=.*/ENABLED=0/' /etc/default/motd-news || true
  fi
}

write_motd() {
  local upd_dir="/etc/update-motd.d"
  if [[ -d "$upd_dir" ]]; then
    cp -a "$upd_dir" "$BACKUP_DIR/update-motd.d.$(date +%s)" || true
    # dynamic component
    cat > "$upd_dir/95-idh-brand" <<'EOF'
#!/usr/bin/env bash
BRAND_FILE="/etc/idh-brand.conf"
[ -f "$BRAND_FILE" ] && . "$BRAND_FILE"
color_start="\033[1;${ANSI_COLOR:-6}m"; color_end="\033[0m"
echo -e "${color_start}# ${BRAND:-Server}${color_end}"
echo -e " Portal: ${PORTAL_URL:-N/A}"
echo -e " Docs:   ${DOC_URL:-N/A}"
echo -e " Support:${SUPPORT_EMAIL:-N/A}"
echo
echo -e " $(uname -sr) • Uptime: $(uptime -p) • IPs: $(hostname -I 2>/dev/null)"
EOF
    chmod +x "$upd_dir/95-idh-brand"
    # keep a golden copy for ensure-service to restore if needed  <— NEW
    install -m 0755 "$upd_dir/95-idh-brand" "$INSTALL_DIR/95-idh-brand"
  else
    # static fallback (rare)
    printf "# %s\nPortal: %s\nDocs:   %s\nSupport:%s\n\nLinux %s • Uptime: %s • IPs: %s\n" \
      "$BRAND" "$PORTAL_URL" "$DOC_URL" "$SUPPORT_EMAIL" \
      "$(uname -sr)" "$(uptime -p)" "$(hostname -I 2>/dev/null)" > /etc/motd
  fi
}

write_issue() {
  # ... (same as before) ...
}

write_profile_prompt() {
  # ... (same as before) ...
}

enable_auto_updates() {
  # ... (same as before) ...
}

write_brand_env() {
  cat > /etc/idh-brand.conf <<EOF
BRAND="${BRAND}"
PORTAL_URL="${PORTAL_URL}"
DOC_URL="${DOC_URL}"
SUPPORT_EMAIL="${SUPPORT_EMAIL}"
ANSI_COLOR="${ANSI_COLOR}"
EOF
}

# NEW: ensure script & systemd units
write_ensure_scripts() {
  install -d /usr/local/sbin /etc/systemd/system

  cat > /usr/local/sbin/idh-ensure-brand.sh <<'ENS'
#!/usr/bin/env bash
set -euo pipefail
# best-effort guard rails to keep branding intact

# load brand env
[ -f /etc/idh-brand.conf ] && . /etc/idh-brand.conf || true

# re-disable vendor motd
if [[ -d /etc/update-motd.d ]]; then
  chmod -x /etc/update-motd.d/* 2>/dev/null || true
  # re-seed our component if missing
  if [[ ! -x /etc/update-motd.d/95-idh-brand && -x /opt/idh-whitelabel/95-idh-brand ]]; then
    install -m 0755 /opt/idh-whitelabel/95-idh-brand /etc/update-motd.d/95-idh-brand
  fi
fi

# ensure ssh banner points to /etc/issue.net
if grep -qE '^\s*#?\s*Banner' /etc/ssh/sshd_config; then
  sed -ri 's|^\s*#?\s*Banner\s+.*|Banner /etc/issue.net|' /etc/ssh/sshd_config || true
else
  echo "Banner /etc/issue.net" >> /etc/ssh/sshd_config
fi
systemctl restart sshd 2>/dev/null || systemctl restart ssh 2>/dev/null || true

# ensure /etc/issue(.net) contain brand header (non-destructive)
ensure_line() {
  local file="$1" text="$2"
  touch "$file"
  grep -Fqx "$text" "$file" || printf "%s\n" "$text" | cat - "$file" > "${file}.tmp" && mv "${file}.tmp" "$file"
}
[ -n "${BRAND:-}" ] && ensure_line /etc/issue     "# ${BRAND}"
[ -n "${BRAND:-}" ] && ensure_line /etc/issue.net "# ${BRAND}"

exit 0
ENS
  chmod 0755 /usr/local/sbin/idh-ensure-brand.sh

  # systemd service - run at boot
  cat > /etc/systemd/system/idh-ensure-brand.service <<'SRV'
[Unit]
Description=Ensure IDH white-label branding persists
After=network-online.target

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/idh-ensure-brand.sh

[Install]
WantedBy=multi-user.target
SRV

  # optional daily timer (enabled by default; can be disabled via flag)
  cat > /etc/systemd/system/idh-ensure-brand.timer <<'TMR'
[Unit]
Description=Run IDH ensure-brand daily

[Timer]
OnBootSec=5min
OnUnitActiveSec=1d
Persistent=true

[Install]
WantedBy=timers.target
TMR

  systemctl enable --now idh-ensure-brand.service >/dev/null 2>&1 || true
  if [[ "${ENSURE_TIMER}" == "on" ]]; then
    systemctl enable --now idh-ensure-brand.timer   >/dev/null 2>&1 || true
  else
    systemctl disable --now idh-ensure-brand.timer  >/dev/null 2>&1 || true
  fi
}

preflight() {
  # ... (same as before) ...
}

main() {
  preflight
  write_brand_env
  set_hostname
  disable_vendor_motd
  write_motd
  write_issue
  write_profile_prompt
  enable_auto_updates || true
  write_ensure_scripts            # <— NEW: install/enable ensure service & timer

  # existing uninstall writer (extended below)
  cat > "$INSTALL_DIR/uninstall.sh" <<'UN'
#!/usr/bin/env bash
set -euo pipefail
BACK="/opt/idh-whitelabel/backup"
# stop/remove ensure units
systemctl disable --now idh-ensure-brand.timer 2>/dev/null || true
systemctl disable --now idh-ensure-brand.service 2>/dev/null || true
rm -f /etc/systemd/system/idh-ensure-brand.service /etc/systemd/system/idh-ensure-brand.timer
systemctl daemon-reload || true

# remove brand files
rm -f /etc/profile.d/idh-brand.sh /etc/idh-brand.conf /usr/local/sbin/idh-ensure-brand.sh
if [[ -d /etc/update-motd.d ]]; then rm -f /etc/update-motd.d/95-idh-brand; fi

# best-effort restore of backups
cp -f "$BACK"/issue.net.* /etc/issue.net 2>/dev/null || true
cp -f "$BACK"/issue.*     /etc/issue     2>/dev/null || true
cp -f "$BACK"/motd.*      /etc/motd      2>/dev/null || true

systemctl restart sshd 2>/dev/null || systemctl restart ssh 2>/dev/null || true
echo "IDH white-label reverted (where backups available)."
UN
  chmod +x "$INSTALL_DIR/uninstall.sh"

  echo
  echo "White-label complete."
  echo "Uninstall: $INSTALL_DIR/uninstall.sh"
}
main
