#!/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
apt-get update
export DEBIAN_FRONTEND=noninteractive
apt-get install -y \
    build-essential \
    libseccomp-dev \
    pkg-config \
    uidmap \
    squashfs-tools \
    squashfuse \
    fuse2fs \
    fuse-overlayfs \
    fakeroot \
    cryptsetup \
    curl wget git
apt-get install -y \
    devscripts \
    debhelper \
    dh-autoreconf \
    help2man \
    libarchive-dev \
    libssl-dev \
    python2 \
    uuid-dev \
    golang-go
# for squashfuse_ll build
apt-get install -y autoconf automake libtool pkg-config libfuse-dev zlib1g-dev

# move source code down a level because debuild writes into parent dir
shopt -s extglob
mkdir src
mv .??* !(src) src

# switch to an unprivileged user with sudo privileges
apt-get 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

cd src

# Be careful not to use unescaped single quotes in these commands
su testuser -c '
  set -x
  set -e
  cp -r dist/debian .
  GOSRC="go$(scripts/get-min-go-version).src.tar.gz"
  if [ -n "$GOSRC" ]; then
    curl -f -L -sS -o debian/$GOSRC https://golang.org/dl/$GOSRC
    if [ -n "'$GO_ARCH'" ]; then
      # Download and install binary too to avoid debuild 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
  # download additional source & patch urls listed in rpm
  SPEC=dist/rpm/apptainer.spec.in
  DOWNLOADURL="$(sed -n "s/^Source[1-9][0-9]*: //p" $SPEC)"
  DOWNLOADURL="$DOWNLOADURL $(sed -n "s/^Patch[1-9][0-9]*: //p" $SPEC)"
  SUBS="$(sed -n "s/.*%global //p" $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))
      BASE="$(basename $URL)"
      curl -f -L -sS -o debian/$BASE $URL
  done
  export DEB_FULLNAME="'"${DEB_FULLNAME:-CI Test}"'"
  export DEBEMAIL="'${DEBEMAIL:-citest@example.com}'"
  debuild --build=binary --no-sign --lintian-opts --display-info --show-overrides
  sudo dpkg -i ../apptainer*.deb

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