#!/bin/sh

set -e
set -x

pairs='
	centos-6:centos/6
	centos-7:centos/7
	centos-8:centos/8
	debian:debian
	'

links='
	debian:ubuntu
	'

tstamp="$(env TZ=UTC date '+%Y%m%d-%H%M')"
tardir='tarballs'

archive_tar_name() {
	echo "$1-$tstamp.tar"
}

archive_tar_gz_name() {
	echo "$1-$tstamp.tar.gz"
}

archive_tar_path() {
	echo "$tardir/$(archive_tar_name "$1")"
}

archive_tar_gz_path() {
	echo "$tardir/$(archive_tar_gz_name "$1")"
}

archives=''

for pair in $pairs; do
	slug="${pair%:*}"
	subdir="${pair#*:}"
	if [ "$slug" = "$pair" ] || [ "$subdir" = "$pair" ] || \
	    [ "$slug" = '' ] || [ "$subdir" = '' ]; then
		echo "Invalid pair '$pair'" 1>&2
		exit 1
	fi
	if ! expr "x$slug" : 'x[a-z0-9-][a-z0-9-]*$' > /dev/null; then
		echo "Invalid characters in the slug of '$pair'" 1>&2
		exit 1
	fi
	if ! expr "x$subdir" : 'x[a-z][a-z0-9/]*[a-z0-9]$' > /dev/null; then
		echo "Invalid characters in the subdir of '$pair'" 1>&2
		exit 1
	fi

	archive_tar="$(archive_tar_path "$slug")"
	archive_tar_gz="$(archive_tar_gz_path "$slug")"

	tar --owner=root --group=root -cf "$archive_tar" -- "$subdir/"
	gzip -9cn -- "$archive_tar" > "$archive_tar_gz"
	rm -f -- "$archive_tar"

	slugs="$slugs $slug"
	archives="$archives $slug:$archive_tar_gz"
done

for pair in $links; do
	src="${pair%:*}"
	dst="${pair#*:}"

	if [ "$src" = "$pair" ] || [ "$dst" = "$pair" ] || \
	    [ "$src" = '' ] || [ "$dst" = '' ]; then
		echo "Invalid link pair '$pair'" 1>&2
		exit 1
	fi
	if ! expr "x$src" : 'x[a-z0-9-][a-z0-9-]*$' > /dev/null; then
		echo "Invalid characters in the source of '$pair'" 1>&2
		exit 1
	fi
	if ! expr "x$dst" : 'x[a-z0-9-][a-z0-9-]*$' > /dev/null; then
		echo "Invalid characters in the destination of '$pair'" 1>&2
		exit 1
	fi

	srcarch="$(archive_tar_gz_name "$src")"
	dstarch="$(archive_tar_gz_path "$dst")"
	rm -f -- "$dstarch"
	ln -s -- "$srcarch" "$dstarch"

	archives="$archives $dst:$dstarch"
done

slugs="${slugs# }"
archives="${archives# }"

for pair in $archives; do
	slug="${pair%:*}"
	src="${pair#*:}"
	dst="$slug.tar.gz"

	rm -f -- "$dst"
	ln -s -- "$src" "$dst"
done

echo "Done with $slugs! ($archives)"
