#!/bin/bash
set -ex

INIT_DEP="rancher/os-bootstrap"
SHARED_DEP="rancher/os-base"
INIT_IMAGES_DST="build/images-init.tar"
SYSTEM_IMAGES_DST="build/images-system.tar"
USER_IMAGES_DST="build/images-user.tar"

cd $(dirname $0)/..

IMAGES=$(bin/host_ros c images -i build/initrd/usr/share/ros/os-config.yml)
INIT_IMAGES=""
SYSTEM_IMAGES=""
USER_IMAGES=""

for i in ${APPEND_SYSTEM_IMAGES};do
    IMAGES="${IMAGES} ${i}"
done

for i in ${IMAGES}; do
    echo "tar-image: pull($i)"
    if ! docker inspect $i >/dev/null 2>&1; then
        docker pull ${i}
    fi

    if [ "${i%%:*}" != "$INIT_DEP" ] ; then
        SYSTEM_IMAGES="$SYSTEM_IMAGES $i"
    fi

    if [ "${i%%:*}" = "$INIT_DEP" ] || [ "${i%%:*}" = "$SHARED_DEP" ] ; then
        INIT_IMAGES="$INIT_IMAGES $i"
    fi
done

for i in ${APPEND_USER_IMAGES}; do
    if ! docker inspect $i >/dev/null 2>&1; then
        docker pull ${i}
    fi
    USER_IMAGES="${USER_IMAGES} ${i}"
done

echo "tar-image: SYSTEM_IMAGES=$SYSTEM_IMAGES"
echo "tar-image: INIT_IMAGES=$INIT_IMAGES"
echo "tar-image: USER_IMAGES=$USER_IMAGES"

if [ "$COMPRESS" == "" ]; then
    ARCHIVE_CMD="gzip"
else
    # system-docker can not load images which compressed by xz with a compression level of 9
    # decompression consumes more memory if using level 9
    # the default compression level for xz is 6
    ARCHIVE_CMD="xz -4 -e"
fi

docker save ${INIT_IMAGES} | ${ARCHIVE_CMD} > ${INIT_IMAGES_DST}
docker save ${SYSTEM_IMAGES} | ${ARCHIVE_CMD} > ${SYSTEM_IMAGES_DST}
if [ ! -z "$USER_IMAGES" ]; then
    docker save ${USER_IMAGES} | ${ARCHIVE_CMD} > ${USER_IMAGES_DST}
fi
echo "tar-images: DONE"
