#!/usr/bin/env bash
# nbdkit
# Copyright Red Hat
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * Neither the name of Red Hat nor the names of its contributors may be
# used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY RED HAT AND CONTRIBUTORS ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RED HAT OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

set -e

# The header.
cat <<'EOF'
/* Generated from nbd-protocol.h by generate-protostrings.sh.
 * License of this file is BSD, the same as the rest of nbdkit.
 */

#include <stdio.h>
#include "nbd-protocol.h"

EOF

declare -A functions=(
    [global_flag]=NBD_FLAG_FIXED_NEWSTYLE
    [flag]=NBD_FLAG_HAS_FLAGS
    [opt]=NBD_OPT_EXPORT_NAME
    [rep]=NBD_REP_ACK
    [info]=NBD_INFO_EXPORT
    [reply]=NBD_REPLY_FLAG_DONE
    [reply_type]=NBD_REPLY_TYPE_NONE
    [cmd]=NBD_CMD_READ
    [cmd_flag]=NBD_CMD_FLAG_FUA
    [error]=NBD_SUCCESS
)

# Generate each 'const char *name_of_nbd_<fn>'
keys=$( printf '%s\n' ${!functions[@]} | sort )
for fn in $keys; do
    echo 'extern const char *'
    echo "name_of_nbd_$fn (unsigned int fl)"
    echo '{'
    echo '  static __thread char buf[] = "unknown (0x00000000)";'
    echo '  switch (fl) {'

    # We look for the first #define <symbol> and rewrite every
    # line up to the next blank line.
    symbol="${functions[$fn]}"
    @SED@ -n "/^#define $symbol/,/^$/p" @srcdir@/nbd-protocol.h |
        @SED@ 's/^#define \([_A-Z]*\).*/  case \1:\
    return "\1\";/'

    echo '  default:'
    echo '    snprintf (buf, sizeof buf, "unknown (0x%x)", fl);'
    echo '    return buf;'
    echo '  }'
    echo '}'
    echo
done
