#!/usr/bin/env bash
#
# package diff script; compare local versions to upstream versions
#
# upstream file will be in 4-column CSV format:
# local_name,URI,branch,hash
# any lines that begin with a # are comments
#
# NOTE: this script is meant for occasional use and is intentionally VERY SIMPLE
# if it becomes more complex, it should be rewritten in python

set -euo pipefail

# read package file
if [[ -n "${1:-}" ]]; then
  packages="$(grep "^$1," upstream | grep --invert-match '\s*#')"
else
  packages="$(grep --invert-match '\s*#' upstream)"
fi


for package in $packages
do
  name="$(echo "$package" | cut --delimiter ',' --fields 1)"
  uri="$(echo "$package" | cut --delimiter ',' --fields 2)"
  branch="$(echo "$package" | cut --delimiter ',' --fields 3)"
  git_hash="$(echo "$package" | cut --delimiter ',' --fields 4)"

  echo "Name:   $name"
  echo "URI:    $uri"
  echo "Branch: $branch"
  echo "Hash:   $git_hash"

  # select hash or branch
  version="$git_hash"

  dir_name="${name}_upstream"

  # if upstream dir doesn't exist, clone it
  if [[ ! -d "$dir_name" ]]; then
    echo "Cloning $uri"
    git clone "$uri" "$dir_name" >/dev/null
  fi

  # make sure our upstream origin matches the configured value
  pushd "$dir_name" >/dev/null
  git remote rm origin || true
  git remote add origin "$uri"
  echo "Fetching $uri"
  git fetch origin >/dev/null 2>&1

  # check out the requested version
  git checkout --force "$version" >/dev/null 2>&1
  popd >/dev/null

  # compare our version to upstream
  diff --unified --recursive --exclude BUILD --exclude .git "$dir_name" "$name" || true

  # add dir_name to local gitignore
  if ! grep -q "$dir_name" .gitignore ; then
    echo "$dir_name" >> .gitignore
  fi
  echo
done
