/* This file is part of Mailfromd testsuite.
   Copyright (C) 2022-2025 Sergey Poznyakoff

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

/*
  NAME
     numck - verify tos traces

  SYNOPSIS
     numck [-c STRING] [-n LINES] [-p] [FILE]

  DESCRIPTION
     Reads tos trace from standard input or FILE and compares each
     number read with the first number.  If the two differ, numck
     prints the number of offending line, the two numbers and exits
     with code 1.

     The input is supposed to be produced by calls to _reg(REG_TOS)
     inserted in the appropriate places of the code.  Apart from 
     numeric lines, it can contain the following:

     * Empty lines
       These are ignored

     * Comments
       Lines beginning with a #, except as followed by + or - sign.

     * Pragmatic comments
       Lines beginning with a #, followed by + or - sign and integer
       number.  Such lines change expected tos value by adding the integer
       with the appropriate sign to the original expectation value.  For
       example:

           100
	   #-3

       After the pragmatic comment above, the expected value becomes 97.
     
  OPTIONS
     -c STRING
       Treat STRING at the beginning of line as comment starter, same
       as #.
     
     -n LINES
       Sets the number of expected input lines.  This number includes
       comments and empty lines.  If the number of lines actually read
       doesn't match that value, an error message is printed and the
       program returns status code 1.

     -p
       Reproduce comment lines on output.
       
  EXIT CODES
     0      Success.
     1      Numeric value read from input doesn't match the expected
            value, or total number of lines processed doesn't match
	    the limit set by the -n option.
     64 (EX_USAGE)
            Command line usage error.
     65 (EX_DATAERR)
            Input is malformed.
     66 (EX_NOINPUT)
            Cannot open input file.

*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <sysexits.h>

enum {
	EX_DIFFER = 1,
};

int
main(int argc, char **argv)
{
	char buf[BUFSIZ];
	long val;
	long lineno = 0;
	long expected_lines = -1;
	int print_comment = 0;
	char *comment_start = NULL;
	size_t comment_start_len = 0;
	int status = EX_OK;
	int init = 0;
	int c;
	char *p;

	while ((c = getopt(argc, argv, "n:c:p")) != EOF) {
		switch (c) {
		case 'c':
			comment_start = optarg;
			comment_start_len = strlen(comment_start);
			break;
		case 'n':
			errno = 0;
			expected_lines = strtol(optarg, &p, 10);
			if (errno || *p || expected_lines < 0) {
				fprintf(stderr, "bad number of expected lines given\n");
				return EX_USAGE;
			}
			break;

		case 'p':
			print_comment = 1;
			break;
			
		default:
			return EX_USAGE;
		}
	}

	switch (argc - optind) {
	case 0:
		break;
	case 1:
		if (!freopen(argv[optind], "r", stdin)) {
			perror(argv[optind]);
			return EX_NOINPUT;
		}
		break;
	default:
		fprintf(stderr, "too many arguments\n");
		return EX_USAGE;
	}
	
	while (fgets(buf, sizeof buf, stdin)) {
		long d;
		size_t len;

		lineno++;
		len = strlen(buf);
		if (buf[len-1] != '\n') {
			int c;
			
			fprintf(stderr, "%ld: line too long\n", lineno);
			while ((c = getchar()) != EOF && c != '\n')
				;
			status = EX_DATAERR;
			continue;
		}
		for (len--; len > 0 && isspace(buf[len-1]); len--)
			;
		if (len == 0)
			continue;
		buf[len] = 0;

		if (buf[0] == '#') {
			if (strchr("+-", buf[1])) {
				errno = 0;
				d = strtol(buf+1, &p, 10);
				if (errno || *p) {
					fprintf(stderr, "%ld: invalid offset\n",
						lineno);
					status = EX_DATAERR;
				}
				val += d;
			}
			if (print_comment)
				printf("%s\n", buf);
			continue;
		} else if (comment_start && len >= comment_start_len &&
			   memcmp(buf, comment_start, comment_start_len) == 0) {
			if (print_comment)
				printf("%s\n", buf);
			continue;
		}			

		errno = 0;
		d = strtol(buf, &p, 10);
		if (errno || *p) {
			fprintf(stderr, "%ld: unrecognized line\n", lineno);
			status = EX_DATAERR;
			continue;
		}

		if (!init) {
			val = d;
			init = 1;
		} else if (d != val) {
			fprintf(stderr, "%ld: %ld != %ld\n", lineno, val, d);
			return EX_DIFFER;
		}
	}

	if (expected_lines != -1 && lineno != expected_lines) {
		fprintf(stderr, "expected %ld lines, but read %ld\n",
			expected_lines, lineno);
		status = EX_DIFFER;
	}	
	return status;
}
