#! /bin/bash
# -*- coding: utf-8 -*-

# This file is part of Cockpit.
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <http://www.gnu.org/licenses/>.

set -e

out=$1
base=$2

# Lookup the newest base image recursively
url=$base
while [ $# -gt 2 ]; do
    pattern="$3"
    newest=`wget -q -O- $url | egrep -o $pattern | sort -V | tail -1`
    if [ -z "$newest" ]; then
        echo "Could not find '$pattern' at: $url" >&2
        exit 1
    fi
    base="$url"
    url="$base/$newest"
    shift
done

if [ -n "$TEST_DATA" -a -f "$TEST_DATA/$newest" ]; then
    echo Using "$TEST_DATA/$newest"
    cp "$TEST_DATA/$newest" "$out"
else

    # we link to the file so wget can properly detect if we have already downloaded it
    # note that due to mirroring, timestamp comparison can result in unnecessary downloading
    out_base=`dirname $out`
    intermediate="$out_base/$newest"

    if [ "$intermediate" != "$out" ]; then
        wget --no-clobber --directory-prefix=$out_base $base/$newest
        cp $intermediate $out
    else
        rm -f $out
        wget --directory-prefix=$out_base $base/$newest
    fi
fi

# Make the image be at least 8 Gig.  During boot, docker-storage-setup
# will grow the partitions etc as appropriate, and atomic.setup will
# explicitly grow the docker pool.

vsize=$(qemu-img info "$out" --output=json | python -c 'import json, sys; print json.load(sys.stdin)["virtual-size"]')

if [ "$vsize" -lt 8589934592 ]; then
    qemu-img resize "$out" 8589934592
fi
