#!/usr/bin/env bash
set -e

# This script downloads manifests, builds, and tables
# from a specified server.
#
# command line:
#    download-manifests.sh  hsca.ipmu.jp/sumire/packages  PACKAGE  VERSION


main()
{
    local server="$1"
    local product="$2"
    local version="$3"

    wget -x http://$server/config.txt
    downloadManifest $server $product $version
}


declare -A g_downloaded

downloadManifest()
{
    local server="$1"
    local product="$2"
    local version="$3"

    if [[ ${g_downloaded["$product-$version"]} == "1" ]]
    then
        return 0
    fi

    # wget 1.16.2 on ubuntu15 won't download an empty file by default.
    # Methinks it is a bug... but we can force wget to download an empty file
    # with '-N' option ("Download it only when revised"). It may seem queer,
    # but it is just what the source code reads.
    wget -x -N \
        http://$server/manifests/$product-$version.manifest \
        http://$server/builds/$product-$version.build \
        http://$server/tables/$product-$version.table \
    || true

    g_downloaded["$product-$version"]="1"

    local pkg_ flavor_ version_ tablefile_ dir_ installID_
    while read -r pkg_ flavor_ version_ tablefile_ dir_ installID_
    do
        downloadManifest $server ${pkg_} ${version_}
    done <<< "$(sed -n \
        -e '1 d'  $(: delete the first line) \
        -e '/^ *#/ d' $(: delete comment lines) \
        -e '{ s/#.*$// ; p }' $(: otherwise, print it) \
        $server/manifests/$product-$version.manifest)"
}

main "$@"
