#!/usr/bin/env bash

set -eEo pipefail

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

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

case "${TARGETPLATFORM}" in
    "linux/arm64")
        ARCH=arm64
        DOCKER_MACHINE_ARCH=aarch64
        DUMB_INIT_ARCH=aarch64
        ;;
    "linux/amd64" | "")
        ARCH=amd64
        DOCKER_MACHINE_ARCH=x86_64
        DUMB_INIT_ARCH=x86_64
        ;;
    "linux/s390x")
        ARCH=s390x
        DOCKER_MACHINE_ARCH=s390x
        DUMB_INIT_ARCH=s390x
        ;;
    "linux/ppc64le")
        ARCH=ppc64le
        DOCKER_MACHINE_ARCH=ppc64le
        DUMB_INIT_ARCH=ppc64le
        ;;
    *)
        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
  curl -L "https://gitlab-docker-machine-downloads.s3.amazonaws.com/${DOCKER_MACHINE_VERSION}/docker-machine-Linux-${DOCKER_MACHINE_ARCH}" \
    -o /usr/bin/docker-machine
else
  echo "No checksum specified for docker-machine, skipping."
fi
curl -L "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


if [[ -f /usr/bin/docker-machine ]]; then
  chmod +x /usr/bin/docker-machine
  docker-machine --version
fi

chmod +x /usr/bin/dumb-init
dumb-init --version
