/*
 * Copyright (c) 2025 Kamo Hiroyasu
 *
 * 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.
 */

/*
 *  call 'cat -n' with the standard output redirected
 *  Author: Kamo Hiroyasu <wd@ics.nara-wu.ac.jp>
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>

int
main(int argc, char *argv[])
{
	pid_t	pid1;
	int	status1;
	int	fd;

	if (argc != 2)
		return 1;
	const char	*path1 = argv[1];
	fd = open(path1, O_WRONLY | O_CREAT | O_TRUNC);
	if (fd == -1) {
		perror(path1);
		return 2;
	}
	if ((pid1 = fork()) == 0) {
		dup2(fd, STDOUT_FILENO);
		if (fd != STDOUT_FILENO) {
			close(fd);
		}
		execl("/bin/cat", "cat", "-n", "--", NULL);
		execl("/usr/bin/cat", "cat", "-n", "--", path1, NULL);
		_exit(1);
	}
	if (pid1 == -1) {
		perror(NULL);
		exit(1);
	}
	close(fd);
	waitpid(pid1, &status1, 0);
	if (!WIFEXITED(status1) || WEXITSTATUS(status1) != 0) {
		fprintf(stderr, "cat failed\n");
		exit(1);
	}
	return 0;
}
