#!/bin/bash -ex
# this script runs as root under docker --privileged

# install dependencies

dnf -y install git gpg golang wget rpm-build
. /etc/os-release
OS_VERSION="${VERSION_ID%.*}"
if [ "$OS_VERSION" -lt 20 ]; then
  # el, not fedora
  dnf install -y epel-release
  dnf install -y epel-rpm-macros
fi
dnf install -y go-rpm-macros

# switch to an unprivileged user
useradd -u 1000 --create-home -s /bin/bash testuser
chown -R testuser .

# Be careful not to use unescaped single quotes in these commands
su testuser -c '
  set -x
  set -e
  VERSION="$(sed -n "s/%global package_version[ \t]*//p" src/openbao.spec)"
  ln -s src openbao-fedora-$VERSION
  tar czhf openbao-fedora-$VERSION.tar.gz --exclude ".git*" openbao-fedora-$VERSION/
  mv openbao-fedora-$VERSION.tar.gz src
  cd src
  DISTURL="`sed -n "s/^Source0: //p" openbao.spec|sed -e "s/%{name}/openbao/g" -e "s/%{package_version}/$VERSION/g"`"
  wget "$DISTURL"
  # eliminate the "dist" part in the rpm name, for the release assets
  rpmbuild -D "dist %{nil}" -D "_topdir $PWD" -D "_sourcedir $PWD" -D "_srcrpmdir $PWD" -D "_rpmdir $PWD" -ba openbao.spec
  mv $(arch)/* .
'

rpm -i src/openbao-*.$(arch).rpm
bao version
