/* Copyright (c) 2026 The Solidite Developers
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, 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 Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>. */

#include <fcntl.h>
#include <locale.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "include/flags.h"

int main(int argc, char* argv[]) {
  setlocale(LC_ALL, "");

  unsigned long options = 1;
  /* options[0]=buffered (-u not encountered)
   * options[1]=don't process options (-- encountered)
   * options[2]=regular stream found
   * options[3]=error occurred (will be return code)
   * decimal 1 same as 0b0001, ISO C99 does not accept 0bXXX*/
  char buf[8192];
  ssize_t n;

  for (int i = 1; i < argc; ++i) {
    if (strcmp(argv[i], "--") == 0)
    set_flag(&options, 1);
    else if (strcmp(argv[i], "-u") == 0 && read_flag(&options, 1) == 0) {
      // implementation is already unbuffered so don't do anything
      set_flag(&options, 0);
      continue;
    } else if (strcmp(argv[i], "-") == 0) {
      set_flag(&options, 2);
      while ((n = read(STDIN_FILENO, buf, sizeof(buf))) > 0)
        (void)write(STDOUT_FILENO, buf, n);
    } else {
      set_flag(&options, 2);
      int fd = open(argv[i], O_RDONLY);
      if (fd == -1) {
        const char ERROR_MESSAGE[] = "failed to open input\n";
        (void)write(STDERR_FILENO, ERROR_MESSAGE, sizeof(ERROR_MESSAGE));
	      set_flag(&options, 3);
	      continue;
      }
      while ((n = read(fd, buf, sizeof(buf))) > 0)
        (void)write(STDOUT_FILENO, buf, n);
      close(fd);
    }
  }

  if (read_flag(&options, 2) == 0) {
    while ((n = read(STDIN_FILENO, buf, sizeof(buf))) > 0)
      (void)write(STDOUT_FILENO, buf, n);
  } // in the case if a stream wasn't provided such as
    // cat being called with "cat -u" or "cat" or "cat --" or "cat -- -u", etc.
  return read_flag(&options, 3);
}
