#!/bin/bash

set -eu
set -o pipefail

SCRIPT_NAME=$(basename $0)
SCRIPT_HOME=$(dirname $0)

function show_options () {
    echo "Usage: $SCRIPT_NAME --download BASE_URL [options] IMAGE_SET"
    echo
    echo "Acquire an image from cache/download it."
    echo
    echo "A BASE_URL needs to be supplied and the image will be downloaded only if"
    echo "the local copy is different. With -c, locally built images are not refreshed"
    echo "while we can do cache invalidation for downloaded images, we don't have cache"
    echo "invalidation logic yet for building images - -c allows direct control."
    echo
    echo "What constitutes an image is determined by the images key of the"
    echo "IMAGE_SET metadata file. This is a json file with the following structure:"
    echo
    echo " {\"images\": ["
    echo "    \"image1_control.qcow2\","
    echo "    \"image2_compute.qcow2\","
    echo "    \"image3_compute_ha.qcow2\","
    echo "    ..."
    echo " ]}"
    echo
    echo "Options:"
    echo "    -c                     -- re-use existing images rather than rebuilding."
    echo "    --download BASE_URL    -- download images from BASE_URL/\$imagename."
    echo "    -h, --help             -- this text."
    echo
    exit $1
}

DOWNLOAD_BASE=
USE_CACHE=

TEMP=$(getopt -o ch -l download:,help -n $SCRIPT_NAME -- "$@")
if [ $? != 0 ] ; then show_options 1; fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
    case "$1" in
        --download) DOWNLOAD_BASE=$2; shift 2;;
        -c) USE_CACHE=1; shift 1;;
        -h | --help) show_options 0;;
        --) shift ; break ;;
        *) echo "Error: unsupported option $1." ; exit 1 ;;
    esac
done

IMAGE_SET=${1:-''}
shift || true

if [ -z "$IMAGE_SET" -o -z "$DOWNLOAD_BASE" ]; then
    show_options 1
fi

IMAGE_BASENAME=$(basename "${IMAGE_SET}")
IMAGE_DIRNAME=$(dirname "${IMAGE_SET}")
METADATA_PATH=$DOWNLOAD_BASE/$IMAGE_BASENAME
CACHE_URL="$TRIPLEO_ROOT/diskimage-builder/elements/cache-url/bin/cache-url"


if [ image_exists -a -n "$USE_CACHE" ]; then
    exit 0
fi

set +e
"${CACHE_URL}" ${METADATA_PATH} ${IMAGE_SET}
RES=$?
set -e
if [ 0 -ne "$RES" -a 44 -ne "$RES" ]; then
    exit $RES
elif [ 44 -ne "$RES" ]; then
    IMG_LIST=$(jq '.images' ${IMAGE_SET})
    for pos in $(seq 0 $(( $(jq length <<< $IMG_LIST) -1  )) ); do
        COMPONENT_NAME=$(jq -r ".[$pos]" <<< $IMG_LIST)
        "${CACHE_URL}" ${DOWNLOAD_BASE}/${COMPONENT_NAME} "${IMAGE_DIRNAME}"/${COMPONENT_NAME}
    done
    exit 0
else
    echo "Error to retrieve the IMAGE_SET meta file."
    exit 1
fi

function image_exists() {
    if [ ! -e "${IMAGE_SET}" ]; then
        return 1
    fi
    IMG_LIST=$(jq '.images' ${IMAGE_SET})
    for pos in $(seq 0 $(($(jq length <<< $IMG_LIST) -1))); do
        COMPONENT_NAME=$(jq -r ".[$pos]" <<< $IMG_LIST)
        if [ ! -e "${IMAGE_DIRNAME}"/${COMPONENT_NAME} ]; then
            return 1
        fi
    done
    return 0
}
