#!/usr/bin/bash
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2022 Frédéric Pierret (fepitre) <frederic@invisiblethingslab.com>
#
# 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 2 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/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later

# This script parses and creates a file containing package info
# necessary for the build process.

set -e
set -o pipefail

# Default redirection or errors
ERR_OUTPUT="/dev/null"

if [ "${DEBUG}" == 1 ]; then
    set -x
    ERR_OUTPUT="/dev/stderr"
fi

if test $# -ne 2; then
	echo "Usage: source_dir directory"
	exit 1
fi

SOURCE_DIR="$1"
ARCHLINUX_DIRECTORY="$2"
DIRECTORY_MANGLE_PATH="${ARCHLINUX_DIRECTORY/$SOURCE_DIR\//}"
DIRECTORY_MANGLE_PATH="${DIRECTORY_MANGLE_PATH//\//_}"
PKGBUILD="${ARCHLINUX_DIRECTORY}/PKGBUILD.in"
# For legacy support
if [ ! -e "$PKGBUILD" ] && [ -e "${PKGBUILD//.in}" ]; then
    PKGBUILD="${ARCHLINUX_DIRECTORY}/PKGBUILD"
fi

# shellcheck disable=SC1090
# shellcheck disable=SC2154
(source "${PKGBUILD}" && printf '%s\n' "${pkgname[@]}" > "${SOURCE_DIR}/${DIRECTORY_MANGLE_PATH}_packages.list" 2>$ERR_OUTPUT)

# shellcheck disable=SC1090
# shellcheck disable=SC2154
(source "${PKGBUILD}" && printf '%s\n' "${arch[0]}" > "${SOURCE_DIR}/${DIRECTORY_MANGLE_PATH}_package_arch" 2>$ERR_OUTPUT)
