#!/bin/bash

set -eu -o pipefail

# KPT-5682: Migrate deprecated positional args in libcare service override.
# The LIBCARE-2400 refactor changed libcare-server from positional args to
# named options (e.g. bare "&3" -> "-S &3"). This script fixes existing
# override.conf files so the service can start with the new binary.

LIBCARE_OVERRIDE=/etc/systemd/system/libcare.service.d/override.conf

if [[ ! -f "$LIBCARE_OVERRIDE" ]]; then
    exit 0
fi

# Replace bare &N socket fd with -S &N on lines containing libcare-server.
# Idempotent: lines already containing -S &N are left unchanged.
#
# How the sed expression works:
#   /libcare-server/{ ... }   — outer address: select only lines with
#                                libcare-server, braces open a nested block
#   /[[:space:]]-S[[:space:]]*&[0-9]+/!  — inner address with !: skip lines
#                                   that already have "-S &N" (idempotency guard)
#   s/[[:space:]]&([0-9]+)/ -S \&\1/g  — replace " &N" with " -S &N";
#                                         [0-9]+ handles multi-digit fds
sed -Ei '/libcare-server/{
  /[[:space:]]-S[[:space:]]*&[0-9]+/! s/[[:space:]]&([0-9]+)/ -S \&\1/g
}' "$LIBCARE_OVERRIDE"

if hash systemctl 2>/dev/null; then
    systemctl daemon-reload
fi
