#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include "debpatch.h"

#define getbyte { byte = fgetc(inf); if (byte == EOF) return 0;}

int do_nh(FILE *of, FILE *inf, int method, int extra) {
	char buf[1024];
	int len;
	int byte;
	int flags;
	int i;
	
	// Header.
	getbyte;
	if (byte != 0x1f) return 0;
	getbyte;
	if (byte != 0x8b) return 0;

	// method.
	getbyte;
	if (byte != method) return 0;

	// flags.
	getbyte;
	flags = byte;

	// timestamp.
	getbyte;
	getbyte;
	getbyte;
	getbyte;

	// Extra flags.
	getbyte;
	if (byte != extra) return 0;

	// OS.
	getbyte;

	// Extra field present.
	if (flags & 0x04) {
		getbyte;
		i = byte;
		getbyte;
		i = (byte << 8);

		for (; i > 0; i--) getbyte;
	}

	// Filename.
	if (flags & 0x08) {
		getbyte;
		while (byte) getbyte;
	}

	// Comment.
	if (flags & 0x10) {
		getbyte;
		while (byte) getbyte;
	}
		
	// Header checksum.
	if (flags & 0x02) {
		getbyte;
		getbyte;
	}


	while (len = fread(buf, 1, 1024, inf)) {
		fwrite(buf, 1, len, of);
	}

	return 1;
}

void do_gznh(FILE *of, char *cmd, int method, int extra) {
	int in[2];
	int out[2];
	FILE *nof;

	pid_t parent;
	pid_t gzpid;
	pid_t nhpid;
	
	if (pipe(in) || pipe(out)) {
		err("Error creating pipes in do_gznh.");
		die();
	}

	parent = getpid();

	gzpid = fork();

	if (gzpid == -1) {
		err("Error creating gzip process.");
		die();
	}

	if (!gzpid) {
		dup2(in[0], 0);
		dup2(out[1], 1);

		close(in[1]);
		close(out[0]);

		execlp("/bin/sh", "/bin/sh", "-c", cmd, NULL);
		exit(-1);
	}

	close(in[0]);
	close(out[1]);
	
	nhpid = fork();

	if (nhpid == -1) {
		err("Couldn't fork gzip header strip process.");

		kill(SIGTERM, gzpid);
		kill(SIGTERM, parent);
		die();
	}

	if (!nhpid) {
		FILE *inf;

		close(in[1]);
		
		inf = fdopen(out[0], "r");
		if (!do_nh(of, inf, method, extra)) {
			err("There was a problem with the gzip header.");
			kill(SIGTERM, gzpid);
			kill(SIGTERM, parent);
			die();
		}

		exit(0);		
	}

	close (out[0]);

	nof = fdopen(in[1], "w");
	add_2pipe(nof, gzpid, nhpid);
}
	
	
		
