#!/usr/bin/env bash
set -Eeuo pipefail

INSTALL_ROOT=/opt/date-integration
DATA_ROOT=/srv/date-integration
DATA_DEVICE_PATH='${data_device_path}'

export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y ca-certificates curl docker.io e2fsprogs jq
systemctl enable --now docker

case "$(uname -m)" in
  x86_64)
    compose_arch=x86_64
    compose_sha256='${compose_sha256_amd64}'
    ;;
  aarch64|arm64)
    compose_arch=aarch64
    compose_sha256='${compose_sha256_arm64}'
    ;;
  *)
    echo "Unsupported architecture: $(uname -m)" >&2
    exit 1
    ;;
esac
compose_url="https://github.com/docker/compose/releases/download/${compose_version}/docker-compose-linux-$compose_arch"
curl -fsSL "$compose_url" -o /usr/local/bin/docker-compose
echo "$compose_sha256  /usr/local/bin/docker-compose" | sha256sum -c -
chmod 0755 /usr/local/bin/docker-compose

data_device=""
for _ in $(seq 1 180); do
  if [[ -e "$DATA_DEVICE_PATH" ]]; then
    data_device="$(readlink -f "$DATA_DEVICE_PATH")"
    break
  fi
  sleep 5
done

if [[ -z "$data_device" ]]; then
  echo "Timed out waiting for data disk at $DATA_DEVICE_PATH" >&2
  exit 1
fi

if ! blkid "$data_device" >/dev/null 2>&1; then
  mkfs.ext4 -F "$data_device"
fi

install -d -m 0750 "$DATA_ROOT"
data_uuid="$(blkid -s UUID -o value "$data_device")"
if ! grep -q "UUID=$data_uuid" /etc/fstab; then
  echo "UUID=$data_uuid $DATA_ROOT ext4 defaults,nofail 0 2" >> /etc/fstab
fi
mountpoint -q "$DATA_ROOT" || mount "$DATA_ROOT"

install -d -m 0700 "$INSTALL_ROOT"
echo '${install_services_b64}' | base64 -d > /usr/local/sbin/date-integration-install
chmod 0700 /usr/local/sbin/date-integration-install
/usr/local/sbin/date-integration-install
echo DATE_INTEGRATION_BOOTSTRAP_READY
