#!/bin/bash -ex
# Copyright (c) Contributors to the Apptainer project, established as
#   Apptainer a Series of LF Projects LLC.
#   For website terms of use, trademark policy, privacy policy and other
#   project policies see https://lfprojects.org/policies

# 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
if [ $OS_TYPE != fedora ]; then
  yum install -y epel-release
fi
yum install -y golang squashfuse fuse-overlayfs fakeroot /usr/*bin/fuse2fs
yum install -y autoconf automake libtool pkgconfig fuse3-devel zlib-devel # for squashfuse_ll build

# 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
  GOURL="$(sed -n "s/^Source1: //p" apptainer.spec)"
  if [ -n "$GOURL" ]; then
    GOSRC="$(basename $GOURL)"
    curl -f -L -sS -o $GOSRC $GOURL
    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
  # enable the multithreading squashfuse
  sed -i "s/^# %\(%global squashfuse_version\)/\1/" apptainer.spec
  # download any additional source & patch urls
  DOWNLOADURL="$(sed -n "s/^Source[1-9][0-9]*: //p" apptainer.spec)"
  DOWNLOADURL="$DOWNLOADURL $(sed -n "s/^Patch[1-9][0-9]*: //p" apptainer.spec)"
  SUBS="$(sed -n "s/^%global //p" apptainer.spec)"
  for URL in $DOWNLOADURL; do
      if [[ "$URL" != http* ]]; then
	  continue
      fi
      URL=$(echo "$SUBS" | (while read FROM TO; do
	      URL="$(echo $URL|sed "s,%{$FROM},$TO,g")"
	    done
	    echo $URL))
      curl -f -L -sS -O $URL
  done
  # 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/apptainer-*)"
  export GOPATH=$BLD/gopath
  PATH=$GOPATH/bin:$PATH

  apptainer exec oras://ghcr.io/apptainer/alpine:3.15.0 /bin/true

  # copy the rpms into the current directory for later use
  cp $HOME/rpmbuild/SRPMS/*.rpm $HOME/rpmbuild/RPMS/*/*.rpm .
'
