#!/bin/bash

echo "*** fake-image-create: start"

echo "arguments:"
echo "----"
echo $*
echo "----"

if [[ "${SHOULD_FAIL}" == 'true' ]]; then
    echo "Should fail is set, exiting with status 127"
    exit 127
fi

if [[ "${DIB_RELEASE}" != "21" ]]; then
    echo "DIB_RELEASE not set correctly"
    exit 1
fi

# test passing of real-life env-vars
if [[ "${TMPDIR}" != "/opt/dib_tmp" ]]; then
    echo "TMPDIR not set"
    exit 1
fi

if [[ "${DIB_IMAGE_CACHE}" != "/opt/dib_cache" ]]; then
    echo "DIB_IMAGE_CACHE not set"
    exit 1
fi

if [[ "${DIB_CLOUD_IMAGES}" != "http://download.fedoraproject.org/pub/fedora/linux/releases/test/21-Beta/Cloud/Images/x86_64/" ]]; then
    echo "DIB_CLOUD_IMAGES not set"
    exit 1
fi

if [[ "${BASE_IMAGE_FILE}" != "Fedora-Cloud-Base-20141029-21_Beta.x86_64.qcow2" ]]; then
    echo "BASE_IMAGE_FILE not set"
    exit 1
fi

outfile=
outtypes=("qcow2")

TEMP=$(getopt -o xo:t: --long qemu-img-options:,no-tmpfs,checksum -- "$@")
if [ $? -ne 0 ]; then
    echo "Invalid option"
    exit 1
fi
eval set -- "$TEMP"
while true ; do
    case "$1" in
        --checksum)
            echo " -> set --checksum"; shift 1;;
        --no-tmpfs)
            echo " -> set --no-tmpfs"; shift 1;;
        --qemu-img-options)
            echo " -> qemu-img-options: $2"; shift 2;;
        -o) outfile=$2; shift 2;;
        -t) IFS="," read -a outtypes <<< "$2"; shift 2;;
        -x) echo " -> debugging enabled"; shift;;
        --) shift ; break ;;
        *) echo "Unknown option : $1"; exit 1;;
    esac
done

if [ -z "$outfile" ]; then
    echo "No output file specified."
    exit 1
else
    for outtype in ${outtypes[@]} ; do
        echo "fake-data" > $outfile.$outtype
        echo "10da41d43d4bd6d67db763616c18b72f" > $outfile.$outtype.md5
        echo "0033e9d444953d11689b5fa6a6dba32bf901582f62b0825bc35f593190b1f7dc" > $outfile.$outtype.sha256
    done
fi

# Emulate manifest creation
mkdir $outfile.d

echo "*** fake-image-create: done"
