#!/bin/bash

set -euo pipefail

if [ $# -lt 2 ]; then
  echo "Usage: $0 <dockerfile> <efs_directory_name> <build_args>..."
  exit 1
fi

dockerfile=$1
efs_directory_name=$2
shift 2

set -- "${@/#/--build-arg=}"

targetpod=$(kubectl get pod -n production -l app=efs-rsync-target -o jsonpath={..metadata.name} --field-selector=status.phase=Running)
if [ -z "$targetpod" ]; then
  echo "Could not find rsync target pod in production namespace"
  exit 1
fi

tmpdir="$(mktemp -d)"
[ -d "$tmpdir" ] || exit 1
trap 'rm -rf "$tmpdir"' EXIT

docker build -f "$dockerfile" "$@" . --output type=tar,dest=- \
  | tar x -C "$tmpdir" --strip-components=1 opt

./krsync.sh \
  --archive \
  --compress \
  --compress-choice=zstd \
  --human-readable \
  --partial \
  --info=progress2 \
  --ignore-times \
  --checksum \
  --delete \
  "$tmpdir/" \
  "$targetpod"@production:/data/"$efs_directory_name"
