#!/usr/bin/env bash

set -eEo pipefail

SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"

TARGETPLATFORM="$1"
DOCKER_MACHINE_VERSION="$2"
DUMB_INIT_VERSION="$3"
GIT_LFS_VERSION="$4"

case "${TARGETPLATFORM}" in
    "linux/arm64")
        ARCH=arm64
        DOCKER_MACHINE_ARCH=aarch64
        DUMB_INIT_ARCH=aarch64
        GIT_LFS_ARCH=arm64
        ;;
    "linux/amd64" | "")
        ARCH=amd64
        DOCKER_MACHINE_ARCH=x86_64
        DUMB_INIT_ARCH=x86_64
        GIT_LFS_ARCH=amd64
        ;;
    "linux/s390x")
        ARCH=s390x
        DOCKER_MACHINE_ARCH=s390x
        DUMB_INIT_ARCH=s390x
        GIT_LFS_ARCH=s390x
        ;;
    *)
        echo "Unexpected TARGETPLATFORM value: ${TARGETPLATFORM}"
        ;;
esac;

"${SCRIPTPATH}/install-gitlab-runner" "${ARCH}"
rm "${SCRIPTPATH}/install-gitlab-runner"
gitlab-runner --version

mkdir -p /etc/gitlab-runner/certs
chmod -R 700 /etc/gitlab-runner

if grep 'docker-machine' "${SCRIPTPATH}/checksums-${ARCH}"; then
  wget -nv "https://github.com/docker/machine/releases/download/v${DOCKER_MACHINE_VERSION}/docker-machine-Linux-${DOCKER_MACHINE_ARCH}" -O /usr/bin/docker-machine
  chmod +x /usr/bin/docker-machine
  docker-machine --version
else
  echo "No checksum specified for docker-machine, skipping."
fi

wget -nv "https://github.com/Yelp/dumb-init/releases/download/v${DUMB_INIT_VERSION}/dumb-init_${DUMB_INIT_VERSION}_${DUMB_INIT_ARCH}" -O /usr/bin/dumb-init
chmod +x /usr/bin/dumb-init
dumb-init --version

wget -nv "https://github.com/git-lfs/git-lfs/releases/download/v${GIT_LFS_VERSION}/git-lfs-linux-${GIT_LFS_ARCH}-v${GIT_LFS_VERSION}.tar.gz" -O /tmp/git-lfs.tar.gz
mkdir /tmp/git-lfs
tar -xf /tmp/git-lfs.tar.gz -C /tmp/git-lfs/
mv /tmp/git-lfs/git-lfs /usr/bin/git-lfs
rm -rf /tmp/git-lfs*
git-lfs install --skip-repo
git-lfs version

sha256sum -c -w "${SCRIPTPATH}/checksums-${ARCH}"
