#!/usr/bin/env bash
# Reject a package that is the wrong kind of file. A Linux executable copied
# into the Windows archive must not pass.
set -euo pipefail

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$root"
mkdir -p dist

appimage="dist/paperdoll-renderer-x86_64.AppImage"
deb="dist/paperdoll-renderer_amd64.deb"
arch="dist/paperdoll-renderer-x86_64.pkg.tar.zst"
windows="dist/paperdoll-renderer-windows-x86_64.zip"

require_file() {
  local path="$1"
  if [[ ! -s "$path" ]]; then
    echo "missing or empty artifact: $path" >&2
    exit 1
  fi
}

magic_prefix() {
  # Print the first bytes as hex, without spaces.
  od -An -tx1 -N "$2" "$1" | tr -d ' \n'
}

require_file "$appimage"
require_file "$deb"
require_file "$arch"
require_file "$windows"

# AppImage 1.9 type 2 images are ELF binaries and contain the AppImage marker.
if [[ "$(magic_prefix "$appimage" 4)" != "7f454c46" ]]; then
  echo "AppImage is not an ELF" >&2
  exit 1
fi
if ! grep -a -q "AppImage" "$appimage"; then
  echo "AppImage marker missing" >&2
  exit 1
fi

# Debian packages are ar archives.
if [[ "$(magic_prefix "$deb" 8)" != "213c617263683e0a" ]]; then
  echo "deb is not an ar archive" >&2
  exit 1
fi

# zstd frame magic.
if [[ "$(magic_prefix "$arch" 4)" != "28b52ffd" ]]; then
  echo "Arch package is not zstd" >&2
  exit 1
fi

# Zip local-file header, a PE executable name, and no ELF header at the start.
if [[ "$(magic_prefix "$windows" 4)" != "504b0304" ]]; then
  echo "Windows artifact is not a zip" >&2
  exit 1
fi
if ! grep -a -q "paperdoll-renderer.exe" "$windows"; then
  echo "Windows zip does not name paperdoll-renderer.exe" >&2
  exit 1
fi
if [[ "$(magic_prefix "$windows" 4)" == "7f454c46" ]]; then
  echo "Windows zip starts with an ELF header" >&2
  exit 1
fi

sha256sum "$appimage" "$deb" "$arch" "$windows" | tee dist/SHA256SUMS
echo "package artifacts verified"
