#!/usr/bin/make -f

include /usr/share/dpkg/pkg-info.mk

# See debhelper(7) (uncomment to enable)
# output every command that modifies files on the build system.
export DH_VERBOSE=1
export PYBUILD_NAME=subscription-manager
export PYBUILD_DISABLE=test
export PYTHON=python3

%:
	dh $@ --with python3 --buildsystem=pybuild

override_dh_auto_build:
	make -f Makefile PREFIX=/usr VERSION=${DEB_VERSION_UPSTREAM_REVISION}

override_dh_auto_clean:
	make clean
	rm -fr build_ext/build_ext/__pycache__

OS_ID := $(shell . /etc/os-release 2>/dev/null && echo $$ID)
OS_VERSION_ID := $(shell . /etc/os-release 2>/dev/null && echo $$VERSION_ID)

# Check if SUSE_IGNORED_RPATHS is defined
HAS_SUSE_IGNORED_RPATHS := $(shell [ -n "$$SUSE_IGNORED_RPATHS" ] && echo 1)

# Check if LOGNAME is set to "abuild"
IS_LOGNAME_ABUILD := $(shell [ "$$LOGNAME" = "abuild" ] && echo 1)

# Default to no
OBS_BUILD := 0

# Conditionally set OBS_BUILD = 1
ifeq ($(HAS_SUSE_IGNORED_RPATHS),1)
  OBS_BUILD := 1
endif

ifeq ($(IS_LOGNAME_ABUILD),1)
  OBS_BUILD := 1
endif

# Default to "no"
# USE_DIST_ENV is used to determine if the dist-packages directory should be used
# This is currently the case for
#  - Ubuntu 24.04
#  - Debian 13
#  - Debian 12 (but only on OBS build)
USE_DIST_ENV := no

ifeq ($(OS_ID),ubuntu)
  ifeq ($(OS_VERSION_ID),24.04)
    USE_DIST_ENV := yes
  endif
endif

ifeq ($(OS_ID),debian)
  ifeq ($(OS_VERSION_ID),13)
    USE_DIST_ENV := yes
  endif
endif

# OpenSuse Build Service Build
ifeq ($(OBS_BUILD),1)
  ifeq ($(OS_ID),debian)
    ifeq ($(OS_VERSION_ID),12)
      USE_DIST_ENV := yes
    endif
  endif
endif

ifeq ($(USE_DIST_ENV),yes)
  PYSITELIB := /usr/lib/python3/dist-packages
else
  PYVER := $(shell python3 -c 'import sys; print("python%s.%s" % sys.version_info[:2])')
  PYSITELIB := /usr/lib/$(PYVER)/site-packages
endif

override_dh_auto_install:
	rm -rf build
	echo "Installing to: $(PYSITELIB)"; \
	DEB_PYTHON_INSTALL_LAYOUT="deb" \
	make -f Makefile install \
	  PREFIX=/usr \
	  DESTDIR="${PWD}/debian/python3-$(PYBUILD_NAME)/" \
	  VERSION="$(DEB_VERSION_UPSTREAM_REVISION)" \
	  PYTHON_SITELIB="$(PYSITELIB)" \
	  PYTHON_INST_DIR="$(PYSITELIB)/subscription_manager" \
	  PYTHON=python3
	# manpages are part of subscription-manager package
	rm -fr ${PWD}/debian/python3-${PYBUILD_NAME}/usr/share/man
	# disable ostre plugin
	sed -i '/^\s*enabled\s*=/d' "${PWD}/debian/python3-${PYBUILD_NAME}/etc/rhsm/pluginconf.d/ostree_content.OstreeContentPlugin.conf"
	echo "enabled = 0" >> "${PWD}/debian/python3-${PYBUILD_NAME}/etc/rhsm/pluginconf.d/ostree_content.OstreeContentPlugin.conf"
	# disable container plugin
	sed -i '/^\s*enabled\s*=/d' "${PWD}/debian/python3-${PYBUILD_NAME}/etc/rhsm/pluginconf.d/container_content.ContainerContentPlugin.conf"
	echo "enabled = 0" >> "${PWD}/debian/python3-${PYBUILD_NAME}/etc/rhsm/pluginconf.d/container_content.ContainerContentPlugin.conf"
