#!/bin/bash -ex

# this script runs as root under docker --privileged

# install dependencies
yum install -y rpm-build make yum-utils gcc binutils util-linux-ng which git
yum install -y libseccomp-devel e2fsprogs cryptsetup
yum install -y epel-release
yum install -y golang

# switch to an unprivileged user with sudo privileges
yum install -y sudo
useradd -u 1000 --create-home -s /bin/bash testuser
echo "Defaults:testuser env_keep=DOCKER_HOST" >>/etc/sudoers
echo "testuser ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
mkdir -p /local
chown -R testuser . /local

# Be careful not to use unescaped single quotes in these commands
su testuser -c '
  set -x
  set -e
  ./mconfig --only-rpm
  GOSRC="$(sed -n "s/^Source1: //p" singularity.spec)"
  if [ -n "$GOSRC" ]; then
    curl -f -L -sS -o $GOSRC https://golang.org/dl/$GOSRC
    if [ -n "'$GO_ARCH'" ]; then
      # Download and install binary too to avoid rpm having to compile the
      #  go toolchain from source
      GOBIN="$(echo "$GOSRC"|sed "s/\.src./.'$GO_ARCH'./")"
      curl -f -L -sS https://golang.org/dl/$GOBIN | tar -xzf - -C /local
      PATH=/local/go/bin:$PATH
    fi
  fi
  go version
  # eliminate the "dist" part in the rpm name, for the release_assets
  echo "%dist %{nil}" >$HOME/.rpmmacros
  make -C builddir rpm
  sudo yum install -y $HOME/rpmbuild/RPMS/*/*.rpm
  BLD="$(echo $HOME/rpmbuild/BUILD/singularity-*)"
  export GOPATH=$BLD/gopath
  PATH=$GOPATH/bin:$PATH

  singularity exec library://alpine:3.11.5 /bin/true

  # copy the rpms into the current directory for the "release_assets" CI
  cp $HOME/rpmbuild/SRPMS/*.rpm $HOME/rpmbuild/RPMS/*/*.rpm .
'
