#!/bin/bash

stream=${1?Choose the wanted fcos stream}

# Setup

WORKING_DIR="build"
mkdir -p ${WORKING_DIR}

# Downloading the latest stream metadata
curl -s -o ${WORKING_DIR}/${stream}.json https://builds.coreos.fedoraproject.org/streams/${stream}.json

fcos_stream=$(jq -r '.stream' < ${WORKING_DIR}/${stream}.json)
fcos_build=$(jq -r '.architectures.x86_64.artifacts.qemu.release' < ${WORKING_DIR}/${stream}.json)
fcos_url=$(jq -r '.architectures.x86_64.artifacts.qemu.formats."qcow2.xz".disk.location' < ${WORKING_DIR}/${stream}.json)
fcos_sha256=$(jq -r '.architectures.x86_64.artifacts.qemu.formats."qcow2.xz".disk.sha256' < ${WORKING_DIR}/${stream}.json)
fcos_image="fcos_${fcos_stream}_${fcos_build}"

# Downloading the latest build image
if [ ! -f ${WORKING_DIR}/${fcos_image}.qcow2.xz ]; then
	echo "Downloading ${fcos_url}"
	if ! curl -s -o ${WORKING_DIR}/${fcos_image}.qcow2.xz ${fcos_url}; then
		echo "Failed to download ${fcos_url}"
		exit 1
	fi
fi

# Checking the archive hash
if ! echo "${fcos_sha256} ${WORKING_DIR}/${fcos_image}.qcow2.xz" | sha256sum -c --quiet; then
	echo "Something went wrong with the archive"
	exit 2
fi

# Uncompress the qcow
echo "Uncompress the downloaded qcow"
xz -qfd ${WORKING_DIR}/${fcos_image}.qcow2.xz

# Generate archive metadatas
timestamp=$(date "+%y%m%d%H%S")
cat <<EOF > ${WORKING_DIR}/metadata.yaml
architecture: x86_64
creation_date: ${timestamp}
properties:
  os: "FedoraCoreOS"
  description: "fcos ${fcos_stream} (${fcos_build})"
  architecture: "x86_64"
EOF

# Building the image archive
echo "Build the archive"
ln -f build/${fcos_image}.qcow2 build/rootfs.img
tar -caf ${WORKING_DIR}/${fcos_image}.tar.xz -C ${WORKING_DIR} metadata.yaml rootfs.img

# Uploading the archive and metadata to incus
echo "Import the archive to incus"
incus image import ${WORKING_DIR}/${fcos_image}.tar.xz --alias fcos/${fcos_stream}

echo "That's all folks !"
