#!/bin/sh

#
# Replace const lines:
#

SRC_JSON=$1
SRC_LINES=$2

if [ "$SRC_LINES" = "" ]; then
  echo "[USAGE]"
  echo "$0 index.json.tmp0 constellationship.fab > 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 ) { \
    line_cnt = 0; \
    const_cnt = 0; \
  } \
  if ( line_cnt < 88 ) { \
    split($0, arr_tmp, " "); \
    const_name = tolower(arr_tmp[1]); \
    n_lines = arr_tmp[2]; \
    str_lines = "["; \
    for ( i=3 ; i <= length(arr_tmp) ; i+=2 ) { \
      if ( 3 < i ) { \
        str_lines = sprintf("%s, ",str_lines); \
      } \
      str_lines = sprintf("%s[%s, %s]",str_lines,arr_tmp[i],arr_tmp[i+1]); \
    } \
    str_lines = sprintf("%s]",str_lines); \
    str_lines_arr[const_name] = sprintf("%c%s%c: %s",34,"lines",34,str_lines); \
    # printf("DEBUG: %d key=%s :: %s\n",line_cnt,const_name,str_lines_arr[const_name]); \
  } \
  else { \
    p0 = match($0, /["]id["]:/); \
    p1 = match($0, /["]CON[ ]modern[ ]/); \
    flg_changed = 0; \
    if ( 0 < p0 && 0 < p1 ) { \
      str_const = tolower(substr($0, p1+12, 3)); \
      # printf("DEBUG: %d: key=%s %s\n",const_cnt,str_const,str_lines_arr[str_const]); \
      const_cnt ++; \
    } \
    else { \
      if ( str_const != "" ) { \
        q0 = match($0, /["]lines["]:[ ]/); \
        if ( 0 < q0 ) { \
          printf("      %s,\n",str_lines_arr[str_const]); \
          flg_changed = 1; \
          str_const = ""; \
        } \
      } \
    } \
    if ( flg_changed == 0 ) { \
      print; \
    } \
  } \
  line_cnt ++; \
  \
}'

