#!/usr/bin/python3

# sd-debian: Software-defined Debian
# Copyright (C) 2024-2026 Daniel Baumann <daniel@debian.org>
# Copyright (C) 2024-2026 Patrik Dufresne <patrik@ikus-soft.com>
#
# SPDX-License-Identifier: GPL-3.0+
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import os
import subprocess
import sys
from pathlib import Path

SD_DEBIAN_BIN = Path("/usr/bin/sd-debian")


def update_hooks_disabled() -> bool:
    """
    Return True if SDD_DISABLE_UPDATE_HOOKS is set to a truthy value.
    """
    value = os.environ.get("SDD_DISABLE_UPDATE_HOOKS", "").strip().lower()
    return value in ("y", "yes", "on", "1", "true", "t")


def main() -> int:
    # Check if sd-debian is executable.
    if not SD_DEBIAN_BIN.is_file() or not os.access(SD_DEBIAN_BIN, os.X_OK):
        return 0

    # Check if hook is disabled.
    if update_hooks_disabled():
        return 0

    try:
        return subprocess.run([str(SD_DEBIAN_BIN), "update"]).returncode
    except OSError:
        return 0


if __name__ == "__main__":
    sys.exit(main())
