%global debug_package %{nil}
%global repo_root %{_topdir}/..
%global base_version %(echo "$(sed -ne '/Version/{s/.*<Version>\\(.*\\)<\\/Version>.*/\\1/p;q;}' < SupportChild.csproj)")

%if %{defined dev_build}
Name:       supportchild-dev
Summary:    A support ticket Discord bot (dev build)
Version:    %{base_version}~%(date "+%%Y%%m%%d%%H%%M%%S")git%(git rev-parse --short HEAD)
Source:     https://toastielab.dev/toastie-stuff/SupportChild/archive/%(git rev-parse HEAD).zip
Provides:   supportchild
%else
Name:       supportchild
Summary:    A support ticket Discord bot
Version:    %{base_version}
Source:     https://toastielab.dev/toastie-stuff/SupportChild/archive/%{base_version}.zip
%endif
Release:    1%{?dist}
License:    GPLv3
URL:        https://toastielab.dev/toastie-stuff/SupportChild
Packager:   Toastie_t0ast

BuildRequires: systemd-rpm-macros
Requires: dotnet-runtime-9.0
%{?systemd_requires}

%description
A support ticket Discord bot. Uses a MySQL database for storage of ticket
information. Creates formatted HTML ticket transcripts when tickets are closed.

%prep
%setup -T -c

%build
dotnet publish %{repo_root}/SupportChild.csproj -p:PublishSingleFile=true -r linux-x64 -c Release --self-contained false --output %{_builddir}/out

%install
if [[ -d %{_rpmdir}/%{_arch} ]]; then
  %{__rm} %{_rpmdir}/%{_arch}/*
fi

%{__install} -d %{buildroot}/usr/bin
# rpmbuild post-processing using the strip command breaks dotnet binaries, remove the executable bit to avoid it
%{__install} -m 644 %{_builddir}/out/supportchild %{buildroot}/usr/bin/supportchild

%{__install} -d %{buildroot}/usr/lib/systemd/system
%{__install} -m 644 %{repo_root}/packaging/supportchild.service %{buildroot}/usr/lib/systemd/system/

%{__install} -d %{buildroot}/etc/supportchild/
%{__install} -m 600 %{repo_root}/default_config.yml %{buildroot}/etc/supportchild/config.yml

%{__install} -d %{buildroot}/var/lib/supportchild/transcripts

%pre
getent group supportchild > /dev/null || groupadd supportchild
getent passwd supportchild > /dev/null || useradd -r -m -d /var/lib/supportchild -s /sbin/nologin -g supportchild supportchild

%post
%systemd_post supportchild.service

%preun
%systemd_preun supportchild.service

%postun
%systemd_postun_with_restart supportchild.service
if [[ "$1" == "0" ]]; then
  getent passwd supportchild > /dev/null && userdel supportchild
fi

%files
%attr(0755,root,root) /usr/bin/supportchild
%attr(0644,root,root) /usr/lib/systemd/system/supportchild.service
%config %attr(0600, supportchild, supportchild) /etc/supportchild/config.yml
%dir %attr(0700, supportchild, supportchild) /var/lib/supportchild
%dir %attr(0755, supportchild, supportchild) /var/lib/supportchild/transcripts