#!/bin/bash
# SPDX-FileCopyrightText: 2026 The NazoOS Contributors
# SPDX-License-Identifier: GPL-3.0-or-later
#
# NazoOS: write /etc/os-release from openSUSE-release's /usr/lib/os-release
# with the NazoOS name, logo and links. /etc/os-release wins over
# /usr/lib/os-release (os-release(5)). Called by nazoos-branding on
# install and after every openSUSE-release update (rpm trigger), so
# VERSION_ID keeps following the Tumbleweed snapshot.
#
# ID/ID_LIKE stay openSUSE's on purpose: zypper plugins, opi, NVIDIA's
# and other installers, distrobox and Steam check them. VARIANT_ID=nazoos
# lets scripts tell NazoOS apart. ADR 0019.
#   nazoos-os-release           write /etc/os-release
#   nazoos-os-release --restore back to openSUSE's symlink

set -eu

# Root of all paths below, set by the tests only (they run as a normal user).
# As root the variable is ignored, so nobody can redirect root's writes
ROOT=
if [ "$(id -u)" -ne 0 ]; then
  ROOT=${NAZOOS_BRANDING_ROOT-}
fi
readonly ROOT

src=$ROOT/usr/lib/os-release
dst=$ROOT/etc/os-release

if [ "${1-}" = --restore ]; then
  ln -sfn ../usr/lib/os-release "$dst"
  exit 0
fi

[ -f "$src" ] || exit 0

tmp=$(mktemp "$ROOT/etc/.os-release.XXXXXX")
{
  echo "# NazoOS: generated by nazoos-branding from $src."
  echo "# Rewritten on every openSUSE-release update, edits are lost."
  sed -E \
    -e '/^(VARIANT|VARIANT_ID)=/d' \
    -e 's/^NAME=.*/NAME="NazoOS"/' \
    -e 's/^PRETTY_NAME=.*/PRETTY_NAME="NazoOS"/' \
    -e 's/^LOGO=.*/LOGO="nazoos-logo"/' \
    -e 's|^HOME_URL=.*|HOME_URL="https://github.com/tokajer/NazoOS"|' \
    -e 's|^BUG_REPORT_URL=.*|BUG_REPORT_URL="https://github.com/tokajer/NazoOS/issues"|' \
    -e 's|^SUPPORT_URL=.*|SUPPORT_URL="https://github.com/tokajer/NazoOS/issues"|' \
    -e 's|^DOCUMENTATION_URL=.*|DOCUMENTATION_URL="https://github.com/tokajer/NazoOS/tree/main/docs"|' \
    "$src"
  echo 'VARIANT="Gaming"'
  echo 'VARIANT_ID="nazoos"'
} > "$tmp"
chmod 0644 "$tmp"
# Replaces openSUSE's symlink atomically
mv -f "$tmp" "$dst"
