#!/usr/bin/env bash

# Small script to test fpc to system error numbers

addtoerrno=0
errnonew=./errno-new.inc

temps="check_errno_list.sh check_reverse_errno_list.sh test-errno* $errnonew"

if [ "$1" == "clean" ] ; then
  echo "Deleting $temps"
  rm -f $temps
  exit
fi

if [ "$1" == "verbose" ] ; then
  verbose=1
  echo "Being verbose"
  shift
else
  verbose=0
fi

if [ "$1" == "addall" ] ; then
  addall=1
  echo "Adding all entries to errno-new.inc"
  shift
else
  addall=0
fi

# Location of error number in system header

errno_headers="/usr/include/asm-generic/errno-base.h /usr/include/asm-generic/errno.h"

if [ "$1" != "" ] ; then
  errno_include=$1
  echo "Using $errno_include file"
else
  errno_include=./errno.inc
fi

# Sustitution made to pass from fpc syscall number
# to system define 
fpc_errno_prefix=ESysE
errno_prefix=E

# Test C file to grab all loaded headers
cat > test-errno.c <<EOF
#include <errno.h>

int
dummy ()
{
  return 0;
}
EOF

# Default C compiler is gcc
# Can be overwritten by setting CC variable
# But I don't know if other compilers also generate
# .i files with --save-temps option
if [ "$CC" == "" ] ; then
  CC=gcc
fi

# Use gcc with --save-temps option to create .i file
$CC --save-temps -c ./test-errno.c
# list of errno.h headers listed
errno_headers_CC=` sed -n "s:.*\"\(.*\.h\)\".*:\1:p" test-errno.i |sort | uniq`
echo "Headers found are \"$errno_headers_CC\""

if [ "$errno_headers_CC" != "" ] ; then
  errno_headers="$errno_headers_CC"
fi


# You should only need to change the variables above

sed -n "s:^[[:space:]]*${fpc_errno_prefix}\\([_a-zA-Z0-9]*\\)[[:space:]]*=[[:space:]]*\\([0-9][0-9]*\\).*:check_errno_number ${errno_prefix}\1 \2:p" ${errno_include} > check_errno_list.sh
sed -n "s:#define[[:space:]]*${errno_prefix}\\([_a-zA-Z0-9]*\\)[[:space:]][[:space:]]*\\(-*[0-9A-Za-z_]*\\)[[:space:]]*\(.*\):check_reverse_errno_number ${fpc_errno_prefix}\1 \2 \"\3\":p" ${errno_headers} > check_reverse_errno_list.sh

function rpad {
  word="$1"
  while [ ${#word} -lt $2 ]; do
    word="$word$3";
  done;
  echo "$word";
}

function compile_errno ()
{
  errname=$1
  errvalue=$2
# Test C file to grab all loaded headers
cat > test-errno.c <<EOF
#include <errno.h>
#include <stdio.h>

int
main ()
{
  printf ("$errname=%d\n",$errname);
  return 0;
}
EOF
$CC -o ./test-errno ./test-errno.c
compiledvalue=`./test-errno`
if [ "$compiledvalue" == "$errname=$errvalue" ] ; then
  if [ $verbose -ne 0 ]; then
    echo "GCC reports $compiledvalue OK"
  fi
else
  echo "GCC reports $compiledvalue, but $errvalue is expected"
fi
}

function check_errno_number ()
{
  sys=$1
  value=$2
  if [ $verbose -ne 0 ] ; then
    echo Testing $sys value $value
  fi
  # Remember value of this constant
  eval ${sys}=${value}
  compile_errno $sys $value

  found=`sed -n "/#define[[:space:]][[:space:]]*${sys}[^A-Za-z0-9_]/p" ${errno_headers}`
  val=`sed -n "s:#define[[:space:]][[:space:]]*${sys}[^A-Za-z0-9_][^A-Za-z0-9_]*\([0-9]*\).*:\1:p" ${errno_headers}`
  extval=`sed -n "s:#define[[:space:]][[:space:]]*${sys}[^A-Za-z0-9_][^A-Za-z0-9_]*\([0-9A-Za-z_]*\).*:\1:p" ${errno_headers}`
  if [ $verbose -ne 0 ] ; then
    echo Test for $sys found \"${found}\" \"${value}\" \"${val}\"
  fi
  if [ "${val}" == "${value}" ] ; then
    if [ $verbose -ne 0 ] ; then
      echo ${sys} value ${val} is correct
    fi
  else
    if [ $verbose -ne 0 ] ; then
      echo "${sys} val=\"$val\", extval=\"$extval\""
    fi
    if [ "${val}" == "" ] ; then
      foundvalue=`sed -n "/#define.*[^A-Za-z0-9_]${value}$/p" ${errno_headers}`
      if [ "${foundvalue}" == "" ] ; then
        foundvalue=`sed -n "s:\/\* ${value} is compa: ${value} is compa:p" ${errno_headers}`
      fi
    fi
    if [ "$extval" != "$val" ] ; then
      eval indirectval=\$$extval
      echo "indirectval =\"$indirectval\" for \"$extval\""
      if [ "$indirectval" != "$value" ] ; then
        echo problem for ${sys} expected ${value}, line is \"${found}\", val found is \"${indirectval}\"
      else
        echo "$sys is defined as $extval which is $indirectval as expected $value"
      fi
    else
      echo "problem for ${sys} expected ${value}, line is \"${found}\", val found is \"${val}\""
    fi
  fi
}

function write_errno_new_head ()
{
  echo "{ File generated by $0" > $errnonew
  uname_info=`uname -s -r -m`
  echo " generated on \"$uname_info\" machine" >> $errnonew
  echo "List of missing system error number found in" >> $errnonew
  echo "$errno_headers" >> $errnonew
  echo "}" >> $errnonew
}

function check_reverse_errno_number ()
{
  errname=$1
  errvalue=$2
  rpaderrname=$(rpad $errname 20 " ")
  if ! [[ "$errvalue" =~ ^[0-9]+$ ]] ; then
    eval errvalue=\$$errvalue
  fi
  
  printf -v padd "%s = %4d" "$rpaderrname" $errvalue

  found=`grep -i -w $1 ${errno_include}`
  comment="$3"
  comment=${comment##\/\*}
  comment=${comment%%\*\/}
  if [ "${found}" == "" ] ; then
    echo "Error ${errname}, value ${errvalue}, not in ${errno_include} file"
    if [ $addtoerrno -eq 0 ] ; then
      addtoerrno=1
      write_errno_new_head
    fi
    echo "        $padd; { $comment }" >> $errnonew
  else
    if [ $addall -eq 1 ] ; then
      if [ $addtoerrno -eq 0 ] ; then
        addtoerrno=1
        write_errno_new_head
      fi
      echo "        $padd; { $comment }" >> $errnonew
    fi
  fi
}

set -f
echo "Checking all entries of ${errno_include} file"
source ./check_errno_list.sh

echo "Checking all defines from \"$errno_header\""
source ./check_reverse_errno_list.sh

if [ $addtoerrno -eq 1 ] ; then
  echo " Missing error number found"
  echo " New values are in \"$errnonew\"
  echo You might want to add these lines to \"$errno_include\""
fi

