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


CONFIG_FILE=/data/gitea/conf/app.ini


ini() {
    local action="$1"
    shift
    crudini "--$action" "$SERVICE_DATASTORE$CONFIG_FILE" "$@"
}


gitea_config_hash() {
    config_hash=$(cat "$SERVICE_DATASTORE$CONFIG_FILE" | md5_compat) || exit 1
    init-config-add "
$MASTER_BASE_SERVICE_NAME:
  labels:
    - compose.config_hash=$config_hash
"

}
join_by_dot() {
    local IFS="."
    echo "$*"
}

gitea:ini-make() {
    local key val type 
    local sep=
    [ -n "$1" ] && printf "\n[%s]\n" "$(IFS="."; echo "$*")"
    while read-0 key type val; do
        case "${type##*\!}" in
            map|seq)
                e "$val" | gitea:ini-make "$@" "$key" || return 1
                continue
                ;;
            bool)
                val="${val%$'\n'}"
                case "${val,,}" in
                    true|ok|yes|y)
                        val=true
                        ;;
                    false|ko|nok|no|n)
                        val=false
                        ;;
                    *)
                        die "Invalid value for ${WHITE}$key$NORMAL, please use a boolean value."
                        ;;
                esac
                ;;
            str|*)
                val="${val%$'\n'}"
                ;;
        esac
        key=${key//-/_}
        key=${key^^}
        printf "%s = %s\n" "$key" "$val"
    done < <( yq -0 'to_entries | map([.key, .value | type, .value | to_yaml])[] | .[]' )
}