#!/bin/bash

set -eo pipefail

# Clean caches etc
filedust -y .

mkdir -p src/sqlcipher
cd sqlcipher && ./configure && make sqlite3.c && cp sqlite3.[ch] ../src/sqlcipher/ && cd ../

# Publish to Pypi
poetry build

# Sign packages
for file in `ls -1 dist/`; do qubes-gpg-client --batch  --armor --detach-sign dist/$file > dist/$file.asc; done

# Deb stuff
DISTS=(
  debian:bookworm
  debian:trixie
  ubuntu:jammy
  ubuntu:noble
)

for dist in ${DISTS[@]}; do
  release=$(echo ${dist} | cut -d: -f2)
  mkdir -p dist/${release}

  docker build -f Dockerfile.debbuild -t bouquin-sqlcipher4-deb:${release} \
    --no-cache \
    --progress=plain \
    --build-arg BASE_IMAGE=${dist} .

  docker run --rm \
    -e SUITE="${release}" \
    -v "$PWD":/src \
    -v "$PWD/dist/${release}":/out \
    bouquin-sqlcipher4-deb:${release}

  find "dist/${release}" -name '*.deb' -print0 \
      | xargs -0 -n1 reprepro -b /home/user/git/repo includedeb "${release}"
done

# RPM
sudo apt-get -y install createrepo-c rpm
BUILD_OUTPUT="${HOME}/git/bouquin-sqlcipher4/dist"
KEYID="54A91143AE0AB4F7743B01FE888ED1B423A3BC99"
REPO_ROOT="${HOME}/git/repo_rpm"
REMOTE="ashpool.mig5.net:/opt/repo_rpm"

DISTS=(
  fedora:43
  fedora:42
)

for dist in ${DISTS[@]}; do
  release=$(echo ${dist} | cut -d: -f2)
  REPO_RELEASE_ROOT="${REPO_ROOT}/${release}"
  RPM_REPO="${REPO_RELEASE_ROOT}/rpm/x86_64"
  mkdir -p "$RPM_REPO"

  docker build \
    --no-cache \
    -f Dockerfile.rpmbuild \
    -t bouquin-sqlcipher4-rpm:${release} \
    --progress=plain \
    --build-arg BASE_IMAGE=${dist} \
    .

  mkdir -p "$PWD/dist/rpm"

  docker run --rm -v "$PWD":/src -v "$PWD/dist/rpm":/out bouquin-sqlcipher4-rpm:${release}
  sudo chown -R "${USER}" "$PWD/dist"

  for file in `ls -1 "${BUILD_OUTPUT}/rpm"`; do
    rpmsign --addsign "${BUILD_OUTPUT}/rpm/$file"
  done

  cp "${BUILD_OUTPUT}/rpm/"*.rpm "$RPM_REPO/"

  createrepo_c "$RPM_REPO"

  echo "==> Signing repomd.xml..."
  qubes-gpg-client --local-user "$KEYID" --detach-sign --armor "$RPM_REPO/repodata/repomd.xml" > "$RPM_REPO/repodata/repomd.xml.asc"
done

echo "==> Syncing repo to server..."
rsync -aHPvz --exclude=.git --delete "$REPO_ROOT/" "$REMOTE/"

poetry publish
echo "Done!"
