#!/bin/bash
#
# makerepropkg - rebuild a package to see if it is reproducible
#
# Copyright (c) 2019 by Eli Schwartz <eschwartz@archlinux.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later

#!/hint/bash
#
# This may be included with or without `set -euE`
#
# SPDX-License-Identifier: GPL-3.0-or-later

[[ -z ${_INCLUDE_COMMON_SH:-} ]] || return 0
_INCLUDE_COMMON_SH="$(set +o|grep nounset)"

set +u +o posix
# shellcheck disable=1091
. /usr/share/makepkg/util.sh
$_INCLUDE_COMMON_SH

# Avoid any encoding problems
export LANG=C

# Set buildtool properties
export BUILDTOOL=devtools
export BUILDTOOLVER=20230105-1-any

# check if messages are to be printed using color
if [[ -t 2 && "$TERM" != dumb ]]; then
	colorize
else
	# shellcheck disable=2034
	declare -gr ALL_OFF='' BOLD='' BLUE='' GREEN='' RED='' YELLOW=''
fi

stat_busy() {
	local mesg=$1; shift
	# shellcheck disable=2059
	printf "${GREEN}==>${ALL_OFF}${BOLD} ${mesg}...${ALL_OFF}" "$@" >&2
}

stat_done() {
	# shellcheck disable=2059
	printf "${BOLD}done${ALL_OFF}\n" >&2
}

_setup_workdir=false
setup_workdir() {
	[[ -z ${WORKDIR:-} ]] && WORKDIR=$(mktemp -d --tmpdir "${0##*/}.XXXXXXXXXX")
	_setup_workdir=true
	trap 'trap_abort' INT QUIT TERM HUP
	trap 'trap_exit' EXIT
}

cleanup() {
	if [[ -n ${WORKDIR:-} ]] && $_setup_workdir; then
		rm -rf "$WORKDIR"
	fi
	exit "${1:-0}"
}

abort() {
	error 'Aborting...'
	cleanup 255
}

trap_abort() {
	trap - EXIT INT QUIT TERM HUP
	abort
}

trap_exit() {
	local r=$?
	trap - EXIT INT QUIT TERM HUP
	cleanup $r
}

die() {
	(( $# )) && error "$@"
	cleanup 255
}

##
#  usage : lock( $fd, $file, $message, [ $message_arguments... ] )
##
lock() {
	# Only reopen the FD if it wasn't handed to us
	if ! [[ "/dev/fd/$1" -ef "$2" ]]; then
		mkdir -p -- "$(dirname -- "$2")"
		eval "exec $1>"'"$2"'
	fi

	if ! flock -n "$1"; then
		stat_busy "${@:3}"
		flock "$1"
		stat_done
	fi
}

##
#  usage : slock( $fd, $file, $message, [ $message_arguments... ] )
##
slock() {
	# Only reopen the FD if it wasn't handed to us
	if ! [[ "/dev/fd/$1" -ef "$2" ]]; then
		mkdir -p -- "$(dirname -- "$2")"
		eval "exec $1>"'"$2"'
	fi

	if ! flock -sn "$1"; then
		stat_busy "${@:3}"
		flock -s "$1"
		stat_done
	fi
}

##
#  usage : lock_close( $fd )
##
lock_close() {
	local fd=$1
	# https://github.com/koalaman/shellcheck/issues/862
	# shellcheck disable=2034
	exec {fd}>&-
}

##
# usage: pkgver_equal( $pkgver1, $pkgver2 )
##
pkgver_equal() {
	if [[ $1 = *-* && $2 = *-* ]]; then
		# if both versions have a pkgrel, then they must be an exact match
		[[ $1 = "$2" ]]
	else
		# otherwise, trim any pkgrel and compare the bare version.
		[[ ${1%%-*} = "${2%%-*}" ]]
	fi
}

##
#  usage: find_cached_package( $pkgname, $pkgver, $arch )
#
#    $pkgver can be supplied with or without a pkgrel appended.
#    If not supplied, any pkgrel will be matched.
##
find_cached_package() {
	local searchdirs=("$PWD" "$PKGDEST") results=()
	local targetname=$1 targetver=$2 targetarch=$3
	local dir pkg packages pkgbasename name ver rel arch r results

	for dir in "${searchdirs[@]}"; do
		[[ -d $dir ]] || continue

		shopt -s extglob nullglob
		mapfile -t packages < <(printf "%s\n" "$dir"/"${targetname}"-"${targetver}"-*"${targetarch}".pkg.tar?(.!(sig|*.*)))
		shopt -u extglob nullglob

		for pkg in "${packages[@]}"; do
			[[ -f $pkg ]] || continue

			# avoid adding duplicates of the same inode
			for r in "${results[@]}"; do
				[[ $r -ef $pkg ]] && continue 2
			done

			# split apart package filename into parts
			pkgbasename=${pkg##*/}
			pkgbasename=${pkgbasename%.pkg.tar*}

			arch=${pkgbasename##*-}
			pkgbasename=${pkgbasename%-"$arch"}

			rel=${pkgbasename##*-}
			pkgbasename=${pkgbasename%-"$rel"}

			ver=${pkgbasename##*-}
			name=${pkgbasename%-"$ver"}

			if [[ $targetname = "$name" && $targetarch = "$arch" ]] &&
					pkgver_equal "$targetver" "$ver-$rel"; then
				results+=("$pkg")
			fi
		done
	done

	case ${#results[*]} in
		0)
			return 1
			;;
		1)
			printf '%s\n' "${results[0]}"
			return 0
			;;
		*)
			error 'Multiple packages found:'
			printf '\t%s\n' "${results[@]}" >&2
			return 1
	esac
}


check_package_validity(){
	local pkgfile=$1
	if grep -q "packager = Unknown Packager" <(bsdtar -xOqf "$pkgfile" .PKGINFO); then
		die "PACKAGER was not set when building package"
	fi
	hashsum=sha256sum
	pkgbuild_hash=$(awk -v"hashsum=$hashsum" -F' = ' '$1 == "pkgbuild_"hashsum {print $2}' <(bsdtar -xOqf "$pkgfile" .BUILDINFO))
	if [[ "$pkgbuild_hash" != "$($hashsum PKGBUILD|cut -d' ' -f1)" ]]; then
		die "PKGBUILD $hashsum mismatch: expected $pkgbuild_hash"
	fi
}


# usage: grep_pkginfo pkgfile pattern
grep_pkginfo() {
	local _ret=()
	mapfile -t _ret < <(bsdtar -xOqf "$1" ".PKGINFO" | grep "^${2} = ")
	printf '%s\n' "${_ret[@]#${2} = }"
}


# Get the package name
getpkgname() {
	local _name

	_name="$(grep_pkginfo "$1" "pkgname")"
	if [[ -z $_name ]]; then
		error "Package '%s' has no pkgname in the PKGINFO. Fail!" "$1"
		exit 1
	fi

	echo "$_name"
}


# Get the package base or name as fallback
getpkgbase() {
	local _base

	_base="$(grep_pkginfo "$1" "pkgbase")"
	if [[ -z $_base ]]; then
		getpkgname "$1"
	else
		echo "$_base"
	fi
}


getpkgdesc() {
	local _desc

	_desc="$(grep_pkginfo "$1" "pkgdesc")"
	if [[ -z $_desc ]]; then
		error "Package '%s' has no pkgdesc in the PKGINFO. Fail!" "$1"
		exit 1
	fi

	echo "$_desc"
}


is_debug_package() {
	local pkgfile=${1} pkgbase pkgname pkgdesc
	pkgbase="$(getpkgbase "${pkgfile}")"
	pkgname="$(getpkgname "${pkgfile}")"
	pkgdesc="$(getpkgdesc "${pkgfile}")"
	[[ ${pkgdesc} == "Detached debugging symbols for "* && ${pkgbase}-debug = "${pkgname}" ]]
}

#!/hint/bash
#
# SPDX-License-Identifier: GPL-3.0-or-later
:

# shellcheck disable=2034
CHROOT_VERSION='v4'

##
#  usage : check_root $keepenv
##
orig_argv=("${BASH_SOURCE[0]}" "$@")
check_root() {
	local keepenv=$1

	(( EUID == 0 )) && return
	if type -P sudo >/dev/null; then
		exec sudo --preserve-env=$keepenv -- "${orig_argv[@]}"
	else
		exec su root -c "$(printf ' %q' "${orig_argv[@]}")"
	fi
}

##
#  usage : is_btrfs( $path )
# return : whether $path is on a btrfs
##
is_btrfs() {
	[[ -e "$1" && "$(stat -f -c %T "$1")" == btrfs ]]
}

##
#  usage : is_subvolume( $path )
# return : whether $path is a the root of a btrfs subvolume (including
#          the top-level subvolume).
##
is_subvolume() {
	[[ -e "$1" && "$(stat -f -c %T "$1")" == btrfs && "$(stat -c %i "$1")" == 256 ]]
}

##
#  usage : subvolume_delete_recursive( $path )
#
#    Find all btrfs subvolumes under and including $path and delete them.
##
subvolume_delete_recursive() {
	local subvol

	is_subvolume "$1" || return 0

	while IFS= read -d $'\0' -r subvol; do
		if ! subvolume_delete_recursive "$subvol"; then
			return 1
		fi
	done < <(find "$1" -mindepth 1 -xdev -depth -inum 256 -print0)
	if ! btrfs subvolume delete "$1" &>/dev/null; then
		error "Unable to delete subvolume %s" "$subvol"
		return 1
	fi

	return 0
}


source /usr/share/makepkg/util/config.sh
source /usr/share/makepkg/util/message.sh

declare -A buildinfo
declare -a buildenv buildopts installed installpkgs

archiveurl='https://archive.archlinux.org/packages'
buildroot=/var/lib/archbuild/reproducible
diffoscope=0

chroot=$USER
[[ -n ${SUDO_USER:-} ]] && chroot=$SUDO_USER
[[ -z "$chroot" || $chroot = root ]] && chroot=copy

parse_buildinfo() {
    local line var val

    while read -r line; do
        var="${line%% = *}"
        val="${line#* = }"
        case ${var} in
            buildenv)
                buildenv+=("${val}")
                ;;
            options)
                buildopts+=("${val}")
                ;;
            installed)
                installed+=("${val}")
                ;;
            *)
                buildinfo["${var}"]="${val}"
                ;;
        esac
    done
}

get_pkgfile() {
    local cdir=${cache_dirs[0]}
    local pkgfilebase=${1}
    local mode=${2}
    local pkgname=${pkgfilebase%-*-*-*}
    local pkgfile ext

    # try without downloading
    if [[ ${mode} != localonly ]] && get_pkgfile "${pkgfilebase}" localonly; then
        return 0
    fi

    for ext in .zst .xz ''; do
        pkgfile=${pkgfilebase}.pkg.tar${ext}

        for c in "${cache_dirs[@]}"; do
            if [[ -f ${c}/${pkgfile} ]]; then
                cdir=${c}
                break
            fi
        done

        for f in "${pkgfile}" "${pkgfile}.sig"; do
            if [[ ! -f "${cdir}/${f}" ]]; then
                if [[ ${mode} = localonly ]]; then
                    continue 2
                fi
                msg2 "retrieving '%s'..." "${f}" >&2
                curl -Llf -# -o "${cdir}/${f}" "${archiveurl}/${pkgname:0:1}/${pkgname}/${f}" || continue 2
            fi
        done
        printf '%s\n' "file://${cdir}/${pkgfile}"
        return 0
    done

    return 1
}

get_makepkg_conf() {
    local fname=${1}
    local arch="${2}"
    local makepkg_conf="${3}"
    if ! buildtool_file=$(get_pkgfile "${fname}"); then
        error "failed to retrieve ${fname}"
        return 1
    fi
    msg2 "using makepkg.conf from ${fname}"
    bsdtar xOqf "${buildtool_file/file:\/\//}" "usr/share/devtools/makepkg-${arch}.conf" > "${makepkg_conf}"
    return 0
}

usage() {
    cat << __EOF__
usage: ${BASH_SOURCE[0]##*/} [options] <package_file>

Run this script in a PKGBUILD dir to build a package inside a
clean chroot while attempting to reproduce it. The package file
will be used to derive metadata needed for reproducing the
package, including the .PKGINFO as well as the buildinfo.

For more details see https://reproducible-builds.org/

OPTIONS
    -d            Run diffoscope if the package is unreproducible
    -c <dir>      Set pacman cache
    -M <file>     Location of a makepkg config file
    -l <chroot>   The directory name to use as the chroot namespace
                  Useful for maintaining multiple copies
                  Default: $chroot
    -h            Show this usage message
__EOF__
}

while getopts 'dM:c:l:h' arg; do
    case "$arg" in
        d) diffoscope=1 ;;
        M) archroot_args+=(-M "$OPTARG") ;;
        c) cache_dirs+=("$OPTARG") ;;
        l) chroot="$OPTARG" ;;
        h) usage; exit 0 ;;
        *|?) usage; exit 1 ;;
    esac
done
shift $((OPTIND - 1))

check_root

[[ -f PKGBUILD ]] || { error "No PKGBUILD in current directory."; exit 1; }

# without arguments, get list of packages from PKGBUILD
if [[ -z $1 ]]; then
    mapfile -t pkgnames < <(source PKGBUILD; pacman -Sddp --print-format '%r/%n' "${pkgname[@]}")
    wait $! || {
        error "No package file specified and failed to retrieve package names from './PKGBUILD'."
        plain "Try '${BASH_SOURCE[0]##*/} -h' for more information." >&2
        exit 1
    }
    msg "Reproducing all pkgnames listed in ./PKGBUILD"
    set -- "${pkgnames[@]}"
fi

# check each package to see if it's a file, and if not, try to download it
# using pacman -Sw, and get the filename from there
splitpkgs=()
for p in "$@"; do
    if [[ -f ${p} ]]; then
        splitpkgs+=("${p}")
    else
        pkgfile_remote=$(pacman -Sddp "${p}" 2>/dev/null) || { error "package name '%s' not in repos" "${p}"; exit 1; }
        pkgfile=${pkgfile_remote#file://}
        if [[ ! -f ${pkgfile} ]]; then
            msg "Downloading package '%s' into pacman's cache" "${pkgfile}"
            sudo pacman -Swdd --noconfirm --logfile /dev/null "${p}" || exit 1
            pkgfile_remote=$(pacman -Sddp "${p}" 2>/dev/null)
            pkgfile="${pkgfile_remote#file://}"
        fi
        splitpkgs+=("${pkgfile}")
    fi
done

for f in "${splitpkgs[@]}"; do
    if ! bsdtar -tqf "${f}" .BUILDINFO >/dev/null 2>&1; then
        error "file is not a valid pacman package: '%s'" "${f}"
        exit 1
    fi
done

if (( ${#cache_dirs[@]} == 0 )); then
	mapfile -t cache_dirs < <(pacman-conf CacheDir)
fi

ORIG_HOME=${HOME}
IFS=: read -r _ _ _ _ _ HOME _ < <(getent passwd "${SUDO_USER:-$USER}")
load_makepkg_config
HOME=${ORIG_HOME}
[[ -d ${SRCDEST} ]] || SRCDEST=${PWD}

parse_buildinfo < <(bsdtar -xOqf "${splitpkgs[0]}" .BUILDINFO)
export SOURCE_DATE_EPOCH="${buildinfo[builddate]}"
PACKAGER="${buildinfo[packager]}"
BUILDDIR="${buildinfo[builddir]}"
BUILDTOOL="${buildinfo[buildtool]}"
BUILDTOOLVER="${buildinfo[buildtoolver]}"
PKGEXT=${splitpkgs[0]#${splitpkgs[0]%.pkg.tar*}}

# nuke and restore reproducible testenv
namespace="$buildroot/$chroot"
lock 9 "${namespace}.lock" "Locking chroot namespace '%s'" "${namespace}"
for copy in "${namespace}"/*/; do
    [[ -d ${copy} ]] || continue
    subvolume_delete_recursive "${copy}"
done
rm -rf --one-file-system "${namespace}"
(umask 0022; mkdir -p "${namespace}")

for fname in "${installed[@]}"; do
    if ! allpkgfiles+=("$(get_pkgfile "${fname}")"); then
        error "failed to retrieve ${fname}"
        exit 1
    fi
done

trap 'rm -rf $TEMPDIR' EXIT INT TERM QUIT
TEMPDIR=$(mktemp -d --tmpdir makerepropkg.XXXXXXXXXX)

makepkg_conf="${TEMPDIR}/makepkg.conf"
# anything before buildtool support is pinned to the last none buildtool aware release
if [[ -z "${BUILDTOOL}" ]]; then
    get_makepkg_conf "devtools-20210202-3-any" "${CARCH}" "${makepkg_conf}" || exit 1
# prefere to assume devtools up until matching makepkg version so repository packages remain reproducible
elif [[ "${BUILDTOOL}" = makepkg ]] && (( $(vercmp "${BUILDTOOLVER}" 6.0.1) <= 0 )); then
    get_makepkg_conf "devtools-20210202-3-any" "${CARCH}" "${makepkg_conf}" || exit 1
# all devtools builds
elif [[ "${BUILDTOOL}" = devtools ]] && get_makepkg_conf "${BUILDTOOL}-${BUILDTOOLVER}" "${CARCH}" "${makepkg_conf}"; then
    true
# fallback to current makepkg.conf
else
    warning "Unknown buildtool (${BUILDTOOL}-${BUILDTOOLVER}), using fallback"
    makepkg_conf=/usr/share/devtools/makepkg-${CARCH}.conf
fi
printf '%s\n' "${allpkgfiles[@]}" | mkarchroot -M "${makepkg_conf}" -U "${archroot_args[@]}" "${namespace}/root" - || exit 1

# use makechrootpkg to prep the build directory
makechrootpkg -r "${namespace}" -l build -- --packagelist || exit 1

# set detected makepkg.conf options
{
    for var in PACKAGER BUILDDIR BUILDTOOL BUILDTOOLVER PKGEXT; do
        printf '%s=%s\n' "${var}" "${!var@Q}"
    done
    printf 'OPTIONS=(%s)\n' "${buildopts[*]@Q}"
    printf 'BUILDENV=(%s)\n' "${buildenv[*]@Q}"
} >> "${namespace}/build"/etc/makepkg.conf
install -d -o "${SUDO_UID:-$UID}" -g "$(id -g "${SUDO_UID:-$UID}")" "${namespace}/build/${BUILDDIR}"

# kick off the build
arch-nspawn "${namespace}/build" \
    --bind="${PWD}:/startdir" \
    --bind="${SRCDEST}:/srcdest" \
    /chrootbuild -C --noconfirm --log --holdver --skipinteg
ret=$?

if (( ${ret} == 0 )); then
    msg2 "built succeeded! built packages can be found in ${namespace}/build/pkgdest"
    msg "comparing artifacts..."

    for pkgfile in "${splitpkgs[@]}"; do
        comparefiles=("${pkgfile}" "${namespace}/build/pkgdest/${pkgfile##*/}")
        if cmp -s "${comparefiles[@]}"; then
            msg2 "Package '%s' successfully reproduced!" "${pkgfile}"
        else
            ret=1
            warning "Package '%s' is not reproducible. :(" "${pkgfile}"
            sha256sum "${comparefiles[@]}"
            if (( diffoscope )); then
                diffoscope "${comparefiles[@]}"
            fi
        fi
    done
fi

# return failure from chrootbuild, or the reproducibility status
exit ${ret}
