#!/usr/bin/env bash

set -eExo pipefail

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

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

INSTALL_ROOT=${DNF_INSTALL_ROOT-}
TARGET_BIN_PATH="${INSTALL_ROOT}/usr/bin"
export PATH="${TARGET_BIN_PATH}:${PATH}"

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 /tmp/docker-machine
  install -m 555 -o 0 -g 0 /tmp/docker-machine ${TARGET_BIN_PATH}/docker-machine
  docker-machine --version
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 /tmp/dumb-init
install -m 555 -o 0 -g 0 /tmp/dumb-init ${TARGET_BIN_PATH}/dumb-init
dumb-init --version
