set -eu

# runc is linked statically, as upstream runc's release binaries are
# (`make static`), with libseccomp built into it.
#
# A dynamically linked runc has to find libseccomp.so at run time, and no
# search path works for every exec: runc re-execs itself as `runc init` from a
# sealed copy (an overlayfs or memfd behind /proc/self/fd/N), with an empty
# environment. That copy cannot see a path relative to the binary, and
# LD_LIBRARY_PATH does not survive, so the loader silently falls back to the
# system libseccomp. An absolute RPATH works only where the package is
# unpacked at /var/vcap/packages/bpm, and the stemcell installs it elsewhere.

source /var/vcap/packages/golang-1-linux/bosh/compile.env

RUNC_VERSION="$(ls runc/runc-*.tar.xz | sed 's/runc\/runc-//' | sed 's/.tar.xz//')"

PKGCONF_VERSION="$(ls pkgconf/pkgconf-*.tar.gz | sed 's|pkgconf/pkgconf-||' | sed 's|.tar.gz||')"
PKG_CONFIG_PREFIX="$(mktemp -d)"

GPERF_VERSION="$(ls gperf/gperf-*.tar.gz | sed 's|gperf/gperf-||' | sed 's|.tar.gz||')"
GPERF_PREFIX="$(mktemp -d)"

LIBSECCOMP_PREFIX="$(mktemp -d)"
LIBSECCOMP_VERSION="$(ls libseccomp/libseccomp-*.tar.gz | sed 's|libseccomp/libseccomp-||' | sed 's|.tar.gz||')"

RUNC_PACKAGE_PATH=github.com/opencontainers/runc

# compile pkgconf
(
  set -eu

  tar xf "pkgconf/pkgconf-${PKGCONF_VERSION}.tar.gz"
  cd "pkgconf-pkgconf-${PKGCONF_VERSION}"
  ./autogen.sh
  ./configure --prefix="${PKG_CONFIG_PREFIX}"
  make
  make install prefix="${PKG_CONFIG_PREFIX}"
  ln -sf pkgconf "${PKG_CONFIG_PREFIX}/bin/pkg-config"
)

# compile gperf
(
  set -eu
  tar xf "gperf/gperf-${GPERF_VERSION}.tar.gz"
  cd "gperf-${GPERF_VERSION}"
  ./configure --prefix="${GPERF_PREFIX}"
  make
  make install
)

# compile libseccomp
(
  set -eu

  export PATH="${GPERF_PREFIX}/bin:$PATH"

  tar xf "libseccomp/libseccomp-${LIBSECCOMP_VERSION}.tar.gz"
  cd "libseccomp-${LIBSECCOMP_VERSION}"
  ./configure --prefix="${LIBSECCOMP_PREFIX}" --enable-static --disable-shared
  make
  make install
)

# install runc
(
  set -eu
  export PATH="${PKG_CONFIG_PREFIX}/bin:$PATH"

  tar xf "runc/runc-${RUNC_VERSION}.tar.xz"
  (
    set -eu
    pushd "runc-${RUNC_VERSION}"
    env \
    PKG_CONFIG_PATH="${LIBSECCOMP_PREFIX}/lib/pkgconfig" \
    GOPROXY=off \
    go build \
      -buildmode=pie \
      -ldflags "-X main.gitCommit=unknown -X main.version=${RUNC_VERSION} -linkmode external -extldflags -static-pie" \
      -tags "seccomp apparmor netgo osusergo" \
	    -mod=vendor \
      -o "${BOSH_INSTALL_TARGET}/bin/runc" \
      .
    popd
  )
)

# clean up source artifacts
rm -r "${PKG_CONFIG_PREFIX}" "${LIBSECCOMP_PREFIX}" "${GPERF_PREFIX}"
