#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define __USE_LARGEFILE64
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

void header(void)
{
	fprintf(stderr, "truncate v0.3, (C) by folkert@vanheusden.com\n\n");
}

int main(int argc, char *argv[])
{
	int c;
	long long int new_size = 0;
	char create = 1;

        while((c = getopt(argc, argv, "c")) != -1)
        {
                switch(c)
                {
                case 'c':
			create = 0;
		default:
			fprintf(stderr, "Internal error!\n");
			return 1;
		}
	}

	if (argc <= 1 || argc > 3)
	{
		header();
		fprintf(stderr, "Usage: file [new size]\n");
		fprintf(stderr, "If new size is omitted, the file will be truncated\n");
		fprintf(stderr, "to 0 bytes.\n");
		return 1;
	}

	if (argc == 3)
	{
		new_size = atoll(argv[2]);
	}

	if (truncate64(argv[1], new_size) == -1)
	{
		if (errno == ENOENT)
		{
			/* the BSD version doesn't treat this as an error, so
			 * we do neither
			 */
			if (create == 0)
				return 0;

			int fd = creat(argv[1], S_IRUSR | S_IWUSR);
			if (fd == -1)
			{
				header();
				fprintf(stderr, "Failed creating new file %s, reason: %s\n", argv[1], strerror(errno));
				return 2;
			}

			if (ftruncate64(fd, new_size) == -1)
			{
				header();
				fprintf(stderr, "Failed to truncate new file %s to size %d, reason: %s\n", argv[1], new_size, strerror(errno));
				return 3;
			}

			close(fd);
		}
		else
		{
			header();
			fprintf(stderr, "Failed to truncate file %s to size %d, reason: %s\n", argv[1], new_size, strerror(errno));
			return 4;
		}
	}

	return 0;
}
