#!/bin/sh

# SPDX-FileCopyrightText: 2021 Andrius Štikonas <andrius@stikonas.eu>
# SPDX-FileCopyrightText: 2021-22 Samuel Tyler <samuel@samuelt.me>
# SPDX-FileCopyrightText: 2021 Paul Dersey <pdersey@gmail.com>
#
# SPDX-License-Identifier: GPL-3.0-or-later

set -ex

# Check tarball checksums
checksum-transcriber sources
sha256sum -c sources.SHA256SUM

mkdir build
cd build

# Extract
ungz --file ${DISTFILES}/${pkg}.tar.gz --output ${pkg}.tar
untar --file ${pkg}.tar
rm ${pkg}.tar
cd ${pkg}

# Prepare
cp ../../mk/main.mk Makefile
catm gzip.c.new ../../files/stat_override.c gzip.c
cp gzip.c.new gzip.c

# Remove generated crc table from util.c
patch -Np1 -i ../../patches/removecrc.patch

# Since IO redirection is not available yet, patch makecrc.c so that it writes
# C code to file crc.c that can be appended to util.c
patch -Np1 -i ../../patches/makecrc-write-to-file.patch

tcc -static -o makecrc sample/makecrc.c
./makecrc
catm util.c.new util.c crc.c
cp util.c.new util.c

# Build
make

# Install
cp gzip ${BINDIR}/gzip
cp gzip ${BINDIR}/gunzip
chmod 755 ${BINDIR}/gzip
chmod 755 ${BINDIR}/gunzip

cd ../..

# Checksums
if match x${UPDATE_CHECKSUMS} xTrue; then
    sha256sum -o ${pkg}.checksums \
        /usr/bin/gzip

    cp ${pkg}.checksums ${SRCDIR}
else
    sha256sum -c ${pkg}.checksums
fi
