# -*- mode: shell-script -*-

CONFIG_FILE=/etc/docker-auth/config.yml
HOST_CONFIG_FILE="$SERVICE_CONFIGSTORE$CONFIG_FILE"

ini_merge_str() {
    local cfg="$1" \
          cache_file="$CACHEDIR/$FUNCNAME.cache.$(p0 "$@" "$(cat "$HOST_CONFIG_FILE")" | md5_compat)" \
          result
    if [ -z "$cfg" ]; then
        return 0
    fi
    if [ -e "$cache_file" ]; then
        #debug "$FUNCNAME: SESSION cache hit $1"
        cat "$cache_file" || return 1
        return 0
    fi

    result="$(merge_yaml_str "$(cat "$HOST_CONFIG_FILE")" "$cfg")" || return 1
    e "$result" | tee "$cache_file" || return 1
}


ini_merge() {
    local result
    result=$(ini_merge_str "$(cat -)")
    e "$result" > "$HOST_CONFIG_FILE"
}


make_users_config() {
    local users_charm_cfg="$1"

    echo "users:"
    while read-0 user config; do
        echo "  \"$user\":"
        password="$config"
        ##$(e "$config" | shyaml get-value password) || return 1
        bcrypt=$(e "$password" | htpasswd -niB "$user" | cut -f 2 -d ":")
        echo "    password: \"$bcrypt\""
    done < <(e "$users_charm_cfg" | shyaml key-values-0)
    echo "  \"\": {}"  ## Allow anonymous
}



registry_config_hash() {
    debug "Adding config hash to enable recreating upon config change."
    config_hash=$(cat "$HOST_CONFIG_FILE" | md5_compat) || exit 1
    init-config-add "
$MASTER_BASE_SERVICE_NAME:
  labels:
    - compose.config_hash=$config_hash
"
}