#!/usr/bin/env sh
# Copyright (C) 2020  Leipzig University Library
#
# 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/>.
#
# @author  Sebastian Kehr <kehr@ub.uni-leipzig.de>
# @license https://opensource.org/licenses/GPL-3.0 GNU GPLv3

# Taken from http://www.etalabs.net/sh_tricks.html
quote () { printf %s\\n "$1" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/'/" ; }

: "${UIDGID:=$(stat -c '%u' .):$(stat -c '%g' .)}"

DIR=data/docker/env; [ -d "$DIR" ] && rm -rf $DIR
mkdir -p "$DIR"; chown "$UIDGID" $DIR/.. $DIR

# shellcheck disable=SC2046
JSON=$(spruce merge $(find docker-env.*.yml) | spruce json)
for KEY in $(echo "$JSON" | jq -r 'keys | join(" ")'); do
  FILE="$DIR/$KEY"; [ -f "$FILE" ] && rm "$FILE"
  for VAR in $(echo "$JSON" | jq -r ".\"$KEY\" | keys | join(\" \")"); do
    VAL=$(echo "$JSON" | jq -r ".\"$KEY\".\"$VAR\"")
    echo "$VAR=$(quote "$VAL")" >> "$FILE"
  done
  chown "$UIDGID" $FILE
done