#!/usr/bin/env lua
--[[
  Copyright (c) 2006-2011 Gordon Gremme <gordon@gremme.org>
  Copyright (c) 2006-2008 Center for Bioinformatics, University of Hamburg

  Permission to use, copy, modify, and distribute this software for any
  purpose with or without fee is hereby granted, provided that the above
  copyright notice and this permission notice appear in all copies.

  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
]]

function usage()
  io.stderr:write(string.format("Usage: %s file [...]\n", arg[0]))
  io.stderr:write("Check C sources for accordance with coding standards.\n")
  os.exit(1)
end

if #arg == 0 then usage() end

error_code = 0

function err(filename, line_number, msg)
  io.stderr:write(string.format("%s: %d: %s\n", filename, line_number, msg))
  error_code = 1
end

function errf(filename, msg)
  io.stderr:write(string.format("%s: %s\n", filename, msg))
  error_code = 1
end

function check_header_file(fn, filecontent)
  local ifndef = filecontent:match("^.-(#ifndef.-)\n")
  local define = filecontent:match("^.-#ifndef.-\n(#define.-)\n")
  local endif  = filecontent:match("\n(#endif)$")
  local define_name
  local had_err = false

  if fn:find("/") then
    define_name = fn:match("^.*/(.+)$")
  else
    define_name = fn;
  end
  define_name = define_name:upper()
  define_name = define_name:gsub("%.", "_")
  define_name = define_name:gsub("%-", "_")

  if (ifndef) then
    local given_name = ifndef:match("#ifndef (.+)")
    if not (given_name == define_name) then
      errf(fn, "first #ifndef should be named '" .. define_name .. "' (is '" ..
           given_name .. "')")
    end
  else
    errf(fn, "does not have #ifndef " .. define_name ..  " line")
  end

  if (define) then
    local given_name = define:match("#define (.+)")
    if not (given_name == define_name) then
      errf(fn, "first #define should be named '" .. define_name .. "' (is '" ..
           given_name .. "')")
    end
  else
    errf(fn, "does not have #define " .. define_name ..
             " line after first #ifndef line")
  end

  if not endif then
    errf(fn, "does not end with plain #endif line")
  end
end

for _, fn in ipairs(arg) do -- iterate over all files
  -- reset per file variables
  local empty_line_found = false
  local ln = 1 -- the line number
  local header_file = false
  local filelines = {}
  local first_line = nil
  local last_line = nil

  if string.find(fn, "%.h$") then
    header_file = true
  end

  for l in io.lines(fn) do -- iterate over all lines
    -- remember first line
    if not first_line then first_line = l end

    -- check for unnecessary blanks
    if string.find(l, " $") then
      err(fn, ln, "unnecessary blank(s) at the end of line")
    end

    -- check for missing blanks
    if string.find(l, " if%(")     then err(fn, ln, "missing blank") end
    if string.find(l, " sizeof%(") then err(fn, ln, "missing blank") end
    if string.find(l, " switch%(") then err(fn, ln, "missing blank") end
    if string.find(l, " while%(")  then err(fn, ln, "missing blank") end
    if string.find(l, " for%(")    then err(fn, ln, "missing blank") end
    if string.find(l, " do%(")     then err(fn, ln, "missing blank") end
    if string.find(l, "%){")       then err(fn, ln, "missing blank") end

    if not string.match(fn, "types_api.h$") then
      -- check for unsigned long long and long long
      if string.find(l, "unsigned%s+long%s+long[%s,%*]") or
         string.find(l, "%(unsigned%s+long%s+long%)") then
        err(fn, ln, "do not use 'unsigned long long', use 'GtUint64' instead")
      elseif string.find(l, "long%s+long[%s,%*]") or
             string.find(l, "%(long%s+long%)") then
        err(fn, ln, "do not use 'long long', use 'GtInt64' instead")
      end

      -- check for unsigned long and long
      if string.find(l, "unsigned%s+long[%s,%*]") or
         string.find(l, "%(unsigned%s+long%)") then
        err(fn, ln, "do not use 'unsigned long', use 'GtUword' instead")
      elseif string.find(l, "%slong[,%*]") or
             string.find(l, "%(long%)") then
        err(fn, ln, "do not use 'long', use 'GtWord' instead")
      end

      -- check flag characters
      if string.find(l, "%%lld") then
        err(fn, ln, "do not use '%lld', use 'GT_LLD' instead")
      end

      if string.find(l, "%%llu") then
        err(fn, ln, "do not use '%llu', use 'GT_LLU' instead")
      end

      if string.find(l, "%%ld") then
        err(fn, ln, "do not use '%ld', use 'GT_WD' instead")
      end

      if string.find(l, "%%lu") then
        err(fn, ln, "do not use '%lu', use 'GT_WU' instead")
      end

      if string.find(l, "%%zu") then
        err(fn, ln, "do not use '%zu', use 'GT_ZU' instead")
      end
    end

    -- check for long double
    if string.find(l, "long double") then
      err (fn, ln, "do not use 'long double', use 'double' instead")
    end

    -- check for superfluous blanks
    if string.find(l, "return  ") then err(fn, ln, "superfluous blank") end

    -- check line length
    if #l > 80 then err(fn, ln, "line longer than 80 characters") end

    -- check for C++ style comments
    if string.find(l, "[^:/\"a-z]//") then err(fn, ln, "C++ style comment") end

    -- check for tabulators
    if string.find(l, "\t") then
      err(fn, ln, "tabulator found, use blanks instead")
    end

    -- check for commata at the beginning of a line
    if string.find(l, "^ *,") then
      err(fn, ln, "illegal ',' at beginning of line")
    end

    -- check for old has_err usage
    if string.find(l, " has_err") then
      err(fn, ln, "illegal variable name 'has_err', use 'had_err' instead")
    end

    -- check for gt library includes with <
    if string.find(l, "^#include <libgt") then
      err(fn, ln, "wrong library include (<...>), use \"...\" instead")
    end

    -- check for tool includes with <
    if string.find(l, "^#include <tools/") then
      err(fn, ln, "wrong tool include (<...>), use \"...\" instead")
    end

    -- check for stdlib assert.h includes and assert(3) usage
    if not string.match(fn, "assert_api.h$") then
      if string.find(l, "^#include <assert.h>") or
         string.find(l, "^#include \"assert.h\"") then
        err(fn, ln,
            "do not include <assert.h>, use \"core/assert_api.h\" instead")
      end
      if string.find(l, " assert%(") then
        err(fn, ln, "do not use assert(), use gt_assert() instead")
      end
    end

    -- check for carriage return
    if string.find(l, "\r") then
      err(fn, ln, "contains carriage return (Windows newline?)")
    end

    -- check for two empty lines in a row
    if string.find(l, "^$") then
      if (empty_line_found) then
        err(fn, ln, "two empty lines in a row")
      end
      empty_line_found = true
    else
      empty_line_found = false
    end

    if (header_file) then
      filelines[ln] = l
    end

    -- remember last line
    last_line = l

    -- increate line number
    ln = ln + 1
  end

  -- make sure first line is not empty
  if first_line and string.find(first_line, "^$") then
    err(fn, 1, "first line is empty")
  end

  -- make sure last line is not empty
  if last_line and string.find(last_line, "^$") then
    err(fn, ln-1, "trailing line is empty")
  end

  if (header_file) then
    local filecontent = table.concat(filelines, "\n")
    check_header_file(fn, filecontent)
  end
end

os.exit(error_code)
