#!/usr/bin/env bash

# If mkosi.builddir/ exists mkosi will set $BUILDDIR to it, let's then use it as
# out-of-tree build dir. Otherwise, let's make up our own builddir.
[ -z "$BUILDDIR" ] && BUILDDIR=build

# After some inspection, we've noticed that:
# `pwd` is: /root/src
# $SRCDIR is: /root/src
# $DESTDIR is: /root/dest

# TODO: Can we use misc/make-path.sh here instead?
# The default that will get used automatically.
export GOPATH=~/go/

# The golang binaries are stored here.
export GOBIN="${GOPATH}bin/"

# Needed so that golang build tools will get found.
export PATH="${GOBIN}:${PATH}"

# Pull from the MKOSI_DEFAULT var: https://github.com/systemd/mkosi/pull/367
mkosi_default="mkosi.default."	# remove this prefix
MGMT_MKOSI_DISTRO="${MKOSI_DEFAULT##$mkosi_default}"

# Lookup the type of image build we're doing.
if [ "${MGMT_MKOSI_DISTRO}" = "" ]; then
	echo "The MGMT_MKOSI_DISTRO variable is empty."
	exit 1
fi
echo "Build distro: $MGMT_MKOSI_DISTRO"

# Arch mirror fixes.
if [ -e "/etc/arch-release" ]; then
	cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.backup
	# Enable all mirrors.
	sed -i 's/^#Server/Server/' /etc/pacman.d/mirrorlist.backup
	#rankmirrors -n 6 /etc/pacman.d/mirrorlist.backup > /etc/pacman.d/mirrorlist	# SLOW
	echo 'Server = http://mirror.rackspace.com/archlinux/$repo/os/$arch' > /etc/pacman.d/mirrorlist
	cat /etc/pacman.d/mirrorlist.backup >> /etc/pacman.d/mirrorlist
	pacman -Syu --noconfirm pacman-mirrorlist
	pacman -Syu
fi

# Get all the dependencies for mgmt.
make deps

# Build it!
make || exit 1

# Store the output.
# TODO: is this required?
mv mgmt $BUILDDIR

# Get the releases directory path.
releases_path=$(make releases_path)	# It captures any other output, careful!
if [ "$releases_path" = "" ]; then
	echo "Releases path is unknown."
	exit 1
fi
mkdir -p "$releases_path"	# Ensure it exists.

echo "The releases_path is: ${releases_path}."

# Build the package for the distribution that we're in.
make release_${MGMT_MKOSI_DISTRO}

# Store releases.
mv "$releases_path${MGMT_MKOSI_DISTRO}/" $BUILDDIR	# mv releases/$(VERSION)/fedora-29/ $BUILDDIR

echo "Done mkosi build!"
