#!/usr/bin/env ruby
# frozen_string_literal: true

# SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
# SPDX-FileCopyrightText: 2021 Harald Sitter <sitter@kde.org>

# This is meant to be used for ExecCondition checks. Exit codes have meaning!
# https://www.freedesktop.org/software/systemd/man/systemd.service.html#ExecCondition=

require 'open3'

LOCKS = %w[
  /var/cache/apt/archives/lock
  /var/lib/dpkg/lock
  /var/lib/dpkg/lock-frontend
].freeze

paths, status = Open3.capture2(*%w[lslocks --raw --output PATH])
exit 255 unless status.success? # can't tell -> fail the unit

paths.split("\n").each do |path|
  next unless LOCKS.any? { |lock| lock == path }

  warn "Lock held: #{path}"
  exit 1
end

exit 0
