#!/bin/sh
set -e

# Add vector:vector user & group
id --user vector >/dev/null 2>&1 || \
  useradd --system --shell /sbin/nologin --home-dir /var/lib/vector --user-group \
    --comment "Vector observability data router" vector

# Create default Vector data directory
mkdir -p /var/lib/vector

# Make vector:vector the owner of the Vector data directory
chown -R vector:vector /var/lib/vector

# Recent versions did not ship /etc/vector/vector.yaml. Preserve both
# untracked files and obsolete conffiles retained from older versions before
# introducing the new stub, avoiding interactive prompts on unattended
# upgrades. postinst restores the user's original content byte-for-byte.
#
# Also preserve obsolete Vector conffiles. If the file belongs to another
# package, leave it alone so dpkg's own file-conflict check reports the
# ownership conflict instead of us silently hiding that package's file.
case "$1" in
  install|upgrade)
    if [ -e /etc/vector/vector.yaml ] && [ ! -L /etc/vector/vector.yaml ]; then
      if ! dpkg-query -W -f='${Conffiles}\n' vector 2>/dev/null \
        | awk '$1 == "/etc/vector/vector.yaml" && $3 != "obsolete" { found = 1 } END { exit !found }' \
        && ! dpkg-query -S /etc/vector/vector.yaml 2>/dev/null \
        | grep -qvE '^vector(:[^: ,]+)?: /etc/vector/vector\.yaml$'; then
        mv /etc/vector/vector.yaml /etc/vector/vector.yaml.vector-preserve
        # An obsolete conffile still has a recorded hash. Leaving its path
        # absent makes dpkg prompt about a deleted configuration file. Stage
        # the exact incoming stub instead, then restore the user's file in
        # postinst (or postrm if installation aborts).
        # The packaging step embeds distribution/debian/vector.yaml here.
        cat > /etc/vector/vector.yaml <<'VECTOR_CONFIG_STUB'
{{config_stub~}}
VECTOR_CONFIG_STUB
      fi
    fi
    ;;
esac

#DEBHELPER#
