#!/bin/bash -e

#
# Sysbox build container initialization script
#

thisHost=$(hostname)-${TARGET_ARCH}

# Build cookie (to build from scratch when necessary only)
if [[ ! -f .buildinfo ]]; then
  touch .buildinfo
  chown rootless:rootless .buildinfo
fi

lastBuildHost=$(cat .buildinfo)
if [[ "$lastBuildHost" != "$thisHost" ]]; then
  make TARGET_ARCH=${TARGET_ARCH} clean
  echo "$thisHost" > .buildinfo
fi

make_target=$1

distro=$(grep "^ID=" /etc/os-release | cut -d "=" -f2)
version=$(grep "^VERSION_ID=" /etc/os-release | cut -d "=" -f2 | tr -d '"')

bin_dir=./build/${distro}_${version}/${TARGET_ARCH}

# Build sysbox
make TARGET_ARCH=${TARGET_ARCH} $make_target --no-print-directory

# Collect build artifacts
mkdir -p ${bin_dir}
cp sysbox-runc/build/${TARGET_ARCH}/sysbox-runc ${bin_dir}
cp sysbox-fs/build/${TARGET_ARCH}/sysbox-fs ${bin_dir}
cp sysbox-mgr/build/${TARGET_ARCH}/sysbox-mgr ${bin_dir}

# For Kinvolk's Flatcar OS, we also build the binaries for fusermount and
# shiftfs (as they are not present in flatcar by default).
if [[ $distro == "flatcar" ]]; then
	build-fusermount ${bin_dir}
	build-shiftfs ${bin_dir}
fi

# Fix ownership of artifacts
chown -R ${HOST_UID}:${HOST_GID} ./build
chown -R ${HOST_UID}:${HOST_GID} ./sysbox-runc/build
chown -R ${HOST_UID}:${HOST_GID} ./sysbox-fs/build
chown -R ${HOST_UID}:${HOST_GID} ./sysbox-mgr/build
chown -R ${HOST_UID}:${HOST_GID} ./sysbox-ipc
chown -R ${HOST_UID}:${HOST_GID} ./sysbox-libs
