#!/bin/bash

# Copyright (c) 2014 The CoreOS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

SCRIPT_ROOT=$(dirname $(readlink -f "$0"))
. "${SCRIPT_ROOT}/common.sh" || exit 1

DEFINE_boolean commit ${FLAGS_FALSE} \
    "Commit all changes after updating."

# Parse flags
FLAGS "$@" || exit 1
eval set -- "${FLAGS_ARGV}"
switch_to_strict_mode

if [[ $# -eq 0 ]]; then
    eval set -- portage-stable coreos-overlay
fi

update_overlay() {
    local repo_name="$1"
    local repo_path=$(portageq get_repo_path / "${repo_name}")
    local job_opts=$(portageq envvar MAKEOPTS)

    info "Updating metadata in ${repo_name}..."
    egencache ${job_opts} --repo="${repo_name}" --update

    pushd "${repo_path}" >/dev/null
    git add -A metadata/md5-cache

    if git diff --quiet --cached; then
        info "Nothing to update in ${repo_name}"
        return 0
    fi

    if [[ ${FLAGS_commit} -eq ${FLAGS_TRUE} ]]; then
        git commit -m "chore(metadata): Regenerate cache" metadata/md5-cache
    else
        git status metadata/md5-cache
    fi
    popd >/dev/null
}

for repo in "$@"; do
    if ! portageq get_repo_path / "$repo" >/dev/null; then
        die_notrace "Unknown repo name '$repo'"
    fi
    update_overlay "$repo"
done

command_completed
