#!/bin/bash

. parse-args "$@"

set -e

enc() {
  echo "$1" | sops encrypt --age "$(cat "$HOME/.ssh/id_rsa.pub")" --filename-override .env
}

dec() {
  echo "$1" | sops decrypt --filename-override .env
}

mapfile -d '' red_paths < <(find . -type f -name '.env' -print0)

for red_path in "${red_paths[@]}"; do
  dir="$(dirname "$red_path")"
  black_path="$dir/black.env"
  [[ -f "$black_path" ]] || enc "" > "$black_path"

  black_old="$(cat "$black_path")"
  red_old=$(dec "$black_old")
  red_new="$(cat "$red_path")"

  if [[ "$red_new" != "$red_old" ]]; then
    black_new="$(enc "$red_new")"
    printf '%s\n' "Updating $black_path" >&2
    printf '%s' "$black_new" > "$black_path"
    git add -- "$black_path"
  else
    printf '%s\n' "No change $black_path" >&2
  fi

done