#!/bin/sh

#
# Replace Asterism lines:
#

SRC_JSON=$1
SRC_LINES=$2

if [ "$SRC_LINES" = "" ]; then
  echo "[USAGE]"
  echo "$0 index.json.tmp1 asterism_lines.json.src.txt > index.json.new"
  exit
fi

AWK_ARG=`sh get_awk-args.sh`

cat $SRC_LINES $SRC_JSON | tr -d '\r' | awk $AWK_ARG '{ \
  \
  if ( NR == 1 ) { \
    flag_eof_src = 0; \
    n_lines_arr = 0; \
    str_ast = ""; \
    flag_ast_part = 0; \
  } \
  if ( flag_eof_src == 0 ) { \
    if ( substr($1,1,1) != "#" ) { \
      p0 = match($0, /["]id["]:/); \
      p1 = match($0, /["]AST[ ]modern[ ]/); \
      if ( 0 < p0 && 0 < p1 ) { \
        str_ast = substr($0, p1+12, 3); \
        # printf("DEBUG: key=%s\n",str_ast); \
        const_cnt ++; \
      } \
      else { \
        if ( str_ast != "" ) { \
          q0 = match($0, /["]common_name["]:/); \
          if ( 0 < q0 ) { \
            names_arr[str_ast] = $0; \
          } \
          q0 = match($0, /["]lines["]:/); \
          if ( 0 < q0 ) { \
            lines_arr[str_ast] = $0; \
            id_arr[n_lines_arr] = str_ast; \
            n_lines_arr ++; \
          } \
        } \
        if ( $1 == "EOF" ) { \
          flag_eof_src = 1; \
          str_ast = ""; \
        } \
      } \
    } \
  } \
  else { \
    p0 = match($0, /["]id["]:/); \
    p1 = match($0, /["]AST[ ]modern[ ]/); \
    if ( 0 < p0 && 0 < p1 ) { \
      flag_ast_part = 1; \
    } \
    else if ( flag_ast_part != 0 && $1 == "}" ) { \
      flag_ast_part = 0; \
      for ( i=0 ; i < n_lines_arr ; i++ ) { \
        key = id_arr[i]; \
        printf("      %c%s%c: %c%s %s %s%c,\n",34,"id",34, 34,"AST","modern",key,34); \
        printf("%s\n",names_arr[key]); \
        printf("%s\n",lines_arr[key]); \
        if ( i + 1 < n_lines_arr ) { \
          printf("    },\n"); \
          printf("    {\n"); \
        } \
      } \
    } \
    if ( flag_ast_part == 0 ) { \
      print; \
    } \
  } \
  \
}'

