#!/bin/sh

channels_url="http://omahaproxy.appspot.com/";
bucket_url="http://commondatastorage.googleapis.com/chromium-browser-official/";
output_file="$(cd "$(dirname "$0")" && pwd)/sources.nix";

get_channels()
{
    for chline in $(echo "$1" | cut -d, -f-2);
    do
        channel="${chline%%,*}";
        version="${chline##*,}";

        url="${bucket_url%/}/chromium-$version.tar.bz2";

        sha256="$(nix-prefetch-url "$url")";

        echo "  $channel = {";
        echo "    version = \"$version\";";
        echo "    url = \"$url\";";
        echo "    sha256 = \"$sha256\";";
        echo "  };";
    done;
}

cd "$(dirname "$0")";

versions="$(curl -s "$channels_url" | sed -n -e 's/^linux,\(\([^,]\+,\)\{2\}\).*$/\1/p')";

if [ -e "$output_file" ];
then
    vhash="$(echo "$versions" | sha256sum | cut -d' ' -f1)";
    old_vhash="$(sed -n 's/# *VHASH: *//p' "$output_file")";

    if [ "x$vhash" = "x$old_vhash" ];
    then
        echo "$output_file is already up to date, bailing out." >&2;
        exit 1;
    fi;
fi;

channels="$(get_channels "$versions")";

cat > "$output_file" <<-EOF
# This file is autogenerated from update.sh in the same directory.
# VHASH: $vhash
{
$channels
}
EOF
