#!/usr/bin/env bash

saved=("$@")
while test $# -gt 0; do
  case "$1" in
    --help|-h)
      printf "Usage:\nprocessrc.sh <filename> <targetname>\n"
      exit 1;;
    esac
    shift
done
set -- "${saved[@]}"

targetname="$2"
arrayName="nativeStringResourceArray_$targetname"
tableName="nativeStringResourceTable_$targetname"

inStringTable=0
inBeginEnd=0
resourceArray=()
while read -r line; do
  if [[ "$line" =~ ^STRINGTABLE[[:space:]]*DISCARDABLE ]]; then
    inStringTable=1
  elif [[ "$line" == "BEGIN" ]]; then
    inBeginEnd="$inStringTable"
  elif [[ "$inBeginEnd" == 1 && "$line" == "END" ]]; then
    inBeginEnd=0
    inStringTable=0
  elif [[ "$inBeginEnd" == 1 && ! "$line" =~ ^[[:space:]]*$ ]]; then
    # Parse line for resource ID
    id="${line%%\"*}"
    # Remove (HRESULT) literal used for casting
    id="${id/(HRESULT)/}"
    # Remove L suffix
    id="${id/L/}"
    # Evaluate expression as integer value
    id="$((id))"

    # Parse line for string content starting with "
    content="${line#*\"}"
    # Remove trailing space
    content="${content%[![:space:]]*}"
    # Remove trailing quotes
    content="${content%\"}"

    resourceArray["$id"]="$content"
  fi
done < "$1"

printf "// Licensed to the .NET Foundation under one or more agreements.\n"
printf "// The .NET Foundation licenses this file to you under the MIT license.\n//\n"
printf "// This code was generated by processrc.sh and is not meant to be modified manually.\n\n"
printf "#include <resourcestring.h>\n\n"
printf "extern NativeStringResourceTable %s;\n" "$tableName"
printf "const NativeStringResource %s[] = {\n" "$arrayName"

for id in "${!resourceArray[@]}"; do
  # ID is printed in hex representation. A string representation that has fewer than 8
  # characters (not including the '0x' prefix) is padded with 0's  to make it 8 characters.
  # Example: an input of 49 yields "0x00000031".
  printf '    {%s,"%s"},\n' "$(printf "0x%08x\n" "$id")" "${resourceArray[$id]}"
done

printf "};\n\n"
printf "NativeStringResourceTable $tableName __attribute__((visibility(\"default\"))) = { %s, %s };\n" "${#resourceArray[@]}" "$arrayName"
