#
# A Gnu-makefile to generate a file (curl_options.c) with all
# current 'CURLOPT_x' values.
#
# By G. Vanem <gvanem@yahoo.no> 2014.
#

empty :=
space := $(empty) $(empty) $(empty)
comma := ,

OPTIONS  = grep '^  CINIT(' ../include/curl/curl.h | cut -f1 -d, | sed 's/CINIT(/CURLOPT_/'
OPTIONS := $(shell $(OPTIONS))

CC     = gcc
CFLAGS = -Wall -I../include

define CURLOPT_TOP
  /*
   * This file has been generated by $(realpath $(MAKEFILE_LIST)) at
   * $(shell date +%d-%B-%Y).
   * DO NOT EDIT!
   */
  #include <curl/curl.h>

  struct key_val {
     unsigned    val;
     const char *name;
     const char *man3_page;
   };

  #define DIM(array)    (sizeof(array) / sizeof((array)[0]))
  #define ADD_OPT(opt)  { opt, #opt, "docs/libcurl/opts/" #opt ".3" }

  static const struct key_val options[] = {
endef

define CURLOPT_BOTTOM
  };

  const char *decode_opt (unsigned opt)
  {
    static char ret[100];
    const char *type = "long";  /* CURLOPTTYPE_LONG == 0 */

    if (opt >= CURLOPTTYPE_OFF_T) {
      opt -= CURLOPTTYPE_OFF_T;
      type = "off_t";
    }
    else if (opt >= CURLOPTTYPE_FUNCTIONPOINT) {
      opt -= CURLOPTTYPE_FUNCTIONPOINT;
      type = "function";
    }
    else if (opt >= CURLOPTTYPE_OBJECTPOINT) {
      opt -= CURLOPTTYPE_OBJECTPOINT;
      type = "object/string";
    }
    snprintf (ret, sizeof(ret), "%3u: %s", opt, type);
    return (ret);
  }

  int main (void)
  {
    const struct key_val *o = options + 0;
    int   i;

    puts ("Idx  CURLOPT_x                              value: arg type      raw value\n"
          "==========================================================================");
    for (i = 0; i < DIM(options); i++, o++)
        printf ("%3d: %-35.35s -> %-20s %u\n",
                i, o->name, decode_opt(o->val), o->val);
    return (0);
  }
endef

all: curl_options

curl_options.c: $(MAKEFILE_LIST)
	$(file > $@, $(CURLOPT_TOP))
	$(foreach o, $(sort $(OPTIONS)), \
	  $(file >> $@, $(space) ADD_OPT ($(o)) $(comma) ) )
	$(file >> $@, $(CURLOPT_BOTTOM))
	@echo '$@ done. $(words $(OPTIONS)) options.'

curl_options: curl_options.c
	$(CC) $(CFLAGS) -o $@ $<

clean:
	rm -f curl_options.*
