#!/bin/bash

set -e

# Manager for building the containers, while using circleci's docker cache workaround.
# Only use 2 images per day to keep the cache size from getting too big and slowing down the build.
# Name of Docker image archives
API="image-api-$(date +%j).tar"
WEBAPP="image-webapp-$(date +%j).tar"

function usage() {
    echo "Usage: $(basename ${0}): load|save" >&2
    exit 1
}

# Load the images if so desired.
function load_images() {
    if [ -e "${HOME}/docker/${API}" ];
    then
        echo "Loading ${API}" >&2
        docker load -i "${HOME}/docker/${API}" | true
    fi

    if [ -e "${HOME}/docker/${WEBAPP}" ];
    then
        echo "Loading ${WEBAPP}" >&2
        docker load -i "${HOME}/docker/${WEBAPP}" | true
    fi
}

# Saves images images.
function save_images() {
    mkdir -p ~/docker
    rm -f ~/docker/*
    echo "Saving ${API}" >&2
    docker save rookeries/api:build > "${HOME}/docker/${API}"
    echo "Saving ${WEBAPP}" >&2
    docker save rookeries/webapp:build > "${HOME}/docker/${WEBAPP}"
    ls -l ~/docker
}

# Main function
if [[ $# -ne 1 ]]; then
    usage
fi

if [ $1 == "load" ]; then
    echo "Loading images..." >&2
    load_images
elif [ $1 == "save" ]; then
    echo "Saving images..." >&2
    save_images
else
    usage
fi
