#!/usr/bin/env bash
#
# Script Name: build-db.sh
# GitLab: https://www.gitlab.com/cabooshyy/cbsh-arch-repo
# Contributors: Cameron Miller

# Set with the flags "-e", "-u","-o pipefail" cause the script to fail
# if certain things happen, which is a good thing.  Otherwise, we can
# get hidden bugs that are hard to discover.
set -euo pipefail

x86_pkgbuild=$(find ../cbsh-arch-pkgbuild/x86_64 -type f -name "*.pkg.tar.zst*")

for x in ${x86_pkgbuild}
do
	    mv "${x}" x86_64/
	        echo "Moving ${x}"
	done

	echo "###########################"
	echo "Building the repo database."
	echo "###########################"

	## Arch: x86_64
	cd x86_64
	rm -f cbsh-arch-repo*

	echo "###################################"
	echo "Building for architecture 'x86_64'."
	echo "###################################"

	## repo-add
	## -s: signs the packages
	## -n: only add new packages not already in database
	## -R: remove old package files when updating their entry
	repo-add -s -n -R cbsh-arch-repo.db.tar.gz *.pkg.tar.zst

	# Removing the symlinks because GitLab can't handle them.
	rm cbsh-arch-repo.db
	rm cbsh-arch-repo.db.sig
	rm cbsh-arch-repo.files
	rm cbsh-arch-repo.files.sig

	# Renaming the tar.gz files without the extension.
	mv cbsh-arch-repo.db.tar.gz cbsh-arch-repo.db
	mv cbsh-arch-repo.db.tar.gz.sig cbsh-arch-repo-db.sig
	mv cbsh-arch-repo.files.tar.gz cbsh-arch-repo.files
	mv cbsh-arch-repo.files.tar.gz.sig cbsh-arch-repo.files.sig

	echo "#######################################"
	echo "Packages in the repo have been updated!"
	echo "#######################################"
