#!/usr/bin/env bash
# vim:et:ts=2:sts=2:sw=2

set -e

say() { echo "[admin] # $*"; }
run() {
  echo "[admin] $ $*"
  "$@"
}

if [ -z "$IS_GITLAB_CI_ENV" ]; then
  echo "This script is for gitlab only" >"/dev/stderr"
  exit 1
fi

if [ -z "$BASE64_BASTION_SSH_KEY" ]; then
  echo "BASE64_BASTION_SSH_KEY is missing!" >"/dev/stderr"
  exit 1
fi

if [ -z "$GITLAB_PACKAGE_TOKEN" ]; then
  echo "GITLAB_PACKAGE_TOKEN is missing!" >"/dev/stderr"
  exit 1
fi

say "Installing required packages"
{
  run pacman -Syu --noconfirm git openssh rsync
}

say "Configuring bastion access"
{
  echo "$BASE64_BASTION_SSH_KEY" | base64 -d >"bastion_key"
  run chmod 0600 "bastion_key"
}

say "Configuring git access"
{
  run git remote add package "https://gitlab-package:$GITLAB_PACKAGE_TOKEN@gitlab.com/techlit-africa/admin"
  # run git checkout main
  # run git pull --tags
}
VERSION="$(git tag -l | sort -V | tail -n1)"

say "Staging scripts"
{
  run git checkout "$VERSION"
  run mkdir stage
  run rsync -avz --exclude='.git' \
    --exclude 'bastion_key' \
    --exclude 'stage' \
    . stage
}

say "Generating changelog and Version file"
{
  git --no-pager log --pretty=format:'%<(18,trunc)%D  %as  %<(16,trunc)%an  %s' >stage/.changelog
  echo "$VERSION" >stage/.version
}

say "Packaging release"
{
  run tar -czf "v$VERSION.tar.gz" -C "stage" .
  sha256sum "v$VERSION"* >"v$VERSION.sha256"
}

say "Uploading release"
{
  run scp -i "bastion_key" \
    -o UserKnownHostsFile=/dev/null \
    -o StrictHostKeyChecking=no \
    "v$VERSION"* "gitlab@artix.techlitafrica.org:/srv/admin"

  run rm -rf "stage"
}
