#!/usr/bin/env bash
#
# Syd: rock-solid application kernel
# dev/release.sh: Release script
#
# Copyright (c) 2023, 2024 Ali Polatel <alip@chesswob.org>
#
# SPDX-License-Identifier: GPL-3.0

set -o errexit

WORK_DIR="$(mktemp -d --tmpdir build-syd.XXXXX)"

OK=true
finish() {
    $OK && rm -rf "${WORK_DIR}"
}

trap finish EXIT

pushd "${WORK_DIR}"

# Establish master connections.
for host in pink syd; do
    echo >&2 "*** ${host} ***"
    ssh root@${host} true
done

for host in pink syd; do
    (
        ssh root@${host} bash <<'EOF'
set -ex

ARCH=$(uname -m)
WORK_DIR="$(mktemp -d ~/tmp/build-syd.XXXXX)"
finish() {
    rm -rf "${WORK_DIR}"
}
trap finish EXIT

pushd "${WORK_DIR}"

git clone https://gitlab.exherbo.org/sydbox/sydbox.git
pushd sydbox
source ~/.cargo/env
rustup update
env \
    LIBSECCOMP_LINK_TYPE=static \
    LIBSECCOMP_LIB_PATH=$(pkg-config --variable=libdir libseccomp || echo /usr/lib) \
    RUSTFLAGS="-Ctarget-feature=+crt-static" \
    cargo build --release --locked -j2
release=target/release
version=$(./${release}/syd --version | head -n1 | awk '{ print $2 }')
distdir=${HOME}/syd-tmp/syd-${version}
rm -rf --one-file-system "${HOME}"/syd-tmp
mkdir -m700 -p "${distdir}"/${ARCH}
cp -ax COPYING README.md src/esyd.sh "${distdir}"
for bin in $(find ${release} -mindepth 1 -maxdepth 1 -type f -executable -name 'syd*'); do
    chmod 755 ${bin}
    mv ${bin} "${distdir}"/${ARCH}
done
EOF
        rsync -ave ssh root@${host}:syd-tmp/ ./
    ) &
done
wait

syd=$(find . -mindepth 1 -maxdepth 1 -type d -name 'syd*' -exec basename '{}' ';')
tar --owner=0 --group=0 -cJvpf ${syd}.tar.xz ${syd}
sha512sum ${syd}.tar.xz > ${syd}.tar.xz.sha512sum
gpg --detach-sign --armor ${syd}.tar.xz.sha512sum
if ! s3cmd put -c ~/.s3cfg.dist -v -P ${syd}.tar.xz* s3://distfiles.exherbo.org/sydbox/
then
    OK=false
    echo >&2 'Upload failed!'
    echo >&2 "Preserving tarballs in ${WORK_DIR}"
fi

popd
