#!/bin/bash
set -e -x

cd $(dirname $0)/..

. ./scripts/version.sh

if [ "${OS}" != "linux" ]; then
  exit
fi

# Used by GHA to inject --platform=linux/(NON_x86_ARCH) on amd64 runners
OPT_ARCH=${1:-""}
if [ -n "${OPT_ARCH}" ]; then
  ARCH=${OPT_ARCH}
  if [ "${ARCH}" = "arm" ]; then
    OPT_PLATFORM="--platform=linux/arm/v6 --platform=linux/arm/v7"
  else
    OPT_PLATFORM="--platform=linux/${ARCH}"
  fi
fi

airgap_image_file='scripts/airgap/image-list.txt'
images=$(cat "${airgap_image_file}")
xargs -tn1 ctr -n moby images pull ${OPT_PLATFORM} 1> /dev/null <<< "${images}" || true
ctr -n moby images export ${OPT_PLATFORM} dist/artifacts/k3s-airgap-images-${ARCH}.tar ${images}
zstd --no-progress -T0 -16 -f --long=25 dist/artifacts/k3s-airgap-images-${ARCH}.tar -o dist/artifacts/k3s-airgap-images-${ARCH}.tar.zst
pigz -v -c dist/artifacts/k3s-airgap-images-${ARCH}.tar > dist/artifacts/k3s-airgap-images-${ARCH}.tar.gz
sha256sum dist/artifacts/k3s-airgap-images-${ARCH}.tar* | sed 's|dist/artifacts/||' > dist/artifacts/k3s-airgap-images-${ARCH}.sha256sum
