#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "$0")"

FILES_BIN=(
    "../bin/crio-x86_64-static-glibc"
    "../bin/crio-x86_64-static-musl"
    "../bin/pause-x86_64-static-glibc"
    "../bin/pause-x86_64-static-musl"
)
FILES_MAN=(
    "../docs/crio.8"
    "../docs/crio.conf.5"
)
FILES_ETC=(
    "../crictl.yaml"
    "../crio-umount.conf"
    "../crio.conf"
)
FILES_CONTRIB=(
    "../contrib/cni/10-crio-bridge.conf"
    "../contrib/policy.json"
    "../contrib/systemd/crio-shutdown.service"
    "../contrib/systemd/crio-wipe.service"
    "../contrib/systemd/crio.service"
)
COMPLETIONS="../completions"

TMPDIR=tmp
rm -rf $TMPDIR
mkdir -p $TMPDIR/{bin,contrib,etc,man}

cp -r $COMPLETIONS $TMPDIR

ERRORED=0
for FILE in "${FILES_BIN[@]}"; do
    if [[ ! -f "$FILE" ]]; then
        echo "File '$FILE' does not exist"
        ERRORED=1
    elif [[ ! -x "$FILE" ]]; then
        echo "File '$FILE' is not exectuable"
        ERRORED=1
    elif ! file "$FILE" | grep "statically linked" | grep -q stripped; then
        echo "Binary '$FILE' is not statically linked and stripped"
        ERRORED=1
    else
        cp "$FILE" $TMPDIR/bin
    fi
done

for FILE in "${FILES_MAN[@]}"; do
    if [[ ! -f "$FILE" ]]; then
        echo "File '$FILE' does not exist"
        ERRORED=1
    else
        cp "$FILE" $TMPDIR/man
    fi
done

for FILE in "${FILES_ETC[@]}"; do
    if [[ ! -f "$FILE" ]]; then
        echo "File '$FILE' does not exist"
        ERRORED=1
    else
        cp "$FILE" $TMPDIR/etc
    fi
done
for FILE in "${FILES_CONTRIB[@]}"; do
    if [[ ! -f "$FILE" ]]; then
        echo "File '$FILE' does not exist"
        ERRORED=1
    else
        cp "$FILE" $TMPDIR/contrib
    fi
done

if [[ $ERRORED == 1 ]]; then
    exit 1
fi

cp Makefile $TMPDIR
cp README.md $TMPDIR

# Create the archive
BUNDLE=crio-$(git describe --tags --exact-match 2>/dev/null || git rev-parse --short HEAD)
ARCHIVE="$BUNDLE.tar.gz"
rm -f "$ARCHIVE"
tar cfz "$ARCHIVE" tmp --transform s/tmp/"$BUNDLE"/
rm -rf tmp
echo "Created $(pwd)/$ARCHIVE"

# Test the archive
echo "Testing archive"
tar xf "$ARCHIVE"
pushd "$BUNDLE"
make DESTDIR=test
popd
rm -rf "$BUNDLE"
