#!/bin/bash

set -e -o pipefail

INPUT=$1

function dump
{
    local INDENT=$(printf "%*s" $1 "")
    local TAG=$2
    local BEGIN="^<!--BEGIN $TAG-->$"
    local END="^<!--END-->$"

    if [[ $3 = -remove-deriving ]]; then
        local REMOVE_DERIVING=';s/\[@@deriving.**\]//'
    else
        local REMOVE_DERIVING=''
    fi

    sed -nr "/$BEGIN/,/$END/p" $INPUT | \
        sed -r "/^\`\`\`/d;/^<!--/d;s/^/$INDENT/$REMOVE_DERIVING;s/ *$//"
}

cat<<EOF
(* generated by: $0 $@ *)

open Fieldslib

module Generated_struct = struct
$(dump 2 type_decl)
end

module type Generated_signature_real = sig
$(dump 2 type_decl)
end

module type Generated_signature_docs = sig
$(dump 2 type_decl -remove-deriving)
$(dump 2 generated_sig)
end

module Test_generated_structure : Generated_signature_docs = Generated_struct

module Test_generated_signature : Generated_signature_real = struct
  include (Generated_struct : Generated_signature_docs)
end

module Test_generated_signature_reverse : Generated_signature_docs = struct
  include (Generated_struct : Generated_signature_real)
end


EOF
