#!/bin/bash

# Create a squashfs file from a docker image

set -euo pipefail

if [[ $# != 2 ]]; then
  echo "Usage: $0 <image_name:tag> <output_file>" >&2
  exit 1
fi

image_id=$1
output_file=$2

container_id=$(docker create "${image_id}")
tmpdir="$(mktemp -d)"

cleanup() {
  rm -rf "${tmpdir}"
  docker rm "${container_id}"
}

trap "cleanup" EXIT

docker export -o "${tmpdir}"/rootfs.tar "${container_id}"
mkdir "${tmpdir}"/rootfs
tar -C "${tmpdir}"/rootfs -xf "${tmpdir}"/rootfs.tar
mksquashfs "${tmpdir}"/rootfs "${output_file}"
