#!/bin/bash

# Copyright (C) 2019, 2020 Tim Waugh
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# This is a simple wrapper script to read container.yaml files
# (http://osbs.readthedocs.io/) to find enough information to give to
# retrodep in -diff mode. It also ignores files used for 'dist-git'
# layouts.

if [ $# -lt 1 ]; then
    echo >&2 "Supply VERSION, then optional retrodep flags"
    exit 1
fi
VERSION=$1
shift

# Find import path from container.yaml
MODULES=$(python /dev/fd/3 3<<"EOF" <container.yaml
import sys, yaml
c = yaml.safe_load(sys.stdin)
go = c.get("go")
if go:
    modules = go.get("modules")
    if modules:
        for module in modules:
            print(module["module"] + " " + module.get("path", "."))
EOF
)

if [ -z "$MODULES" ]; then
    MODULES=". ."
fi

if [ -n "$MODULES" ]; then
    (while read module path; do
         # Run retrodep in 'diff' mode, excluding dist-git files
         importpath=
         if [ "$module" != . ]; then
             importpath="-importpath $module"
         fi
    retrodep -diff "$VERSION" -exclude-from /dev/fd/3 $importpath "$@" "$path" 3<<EOF
.git*
Makefile
sources
Dockerfile*
additional-tags
content_sets.yml
container.yaml
.oit
public
scripts
OWNERS
*.bazel
*.bzl
*/*.bazel
*/*.bzl
*/*/*.bazel
*/*/*.bzl
*/*/*/*.bazel
*/*/*/*.bzl
*/*/*/*/*.bazel
*/*/*/*/*.bzl
*/*/*/*/*/*.bazel
*/*/*/*/*/*.bzl
*/*/*/*/*/*/*.bazel
*/*/*/*/*/*/*.bzl
*/*/*/*/*/*/*/*.bazel
*/*/*/*/*/*/*/*.bzl
*/*/*/*/*/*/*/*/*.bazel
*/*/*/*/*/*/*/*/*.bzl
*/*/*/*/*/*/*/*/*/*.bazel
*/*/*/*/*/*/*/*/*/*.bzl
*/*/*/*/*/*/*/*/*/*/*.bazel
*/*/*/*/*/*/*/*/*/*/*.bzl
*/*/*/*/*/*/*/*/*/*/*/*.bazel
*/*/*/*/*/*/*/*/*/*/*/*.bzl
*/*/*/*/*/*/*/*/*/*/*/*/*.bazel
*/*/*/*/*/*/*/*/*/*/*/*/*.bzl
*/*/*/*/*/*/*/*/*/*/*/*/*/*.bazel
*/*/*/*/*/*/*/*/*/*/*/*/*/*.bzl
*/*/*/*/*/*/*/*/*/*/*/*/*/*/*.bazel
*/*/*/*/*/*/*/*/*/*/*/*/*/*/*.bzl
*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*.bazel
*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*.bzl
EOF
    done) <<<"$MODULES"
fi
