#include "cmdlib.h"
#include <sys/types.h>
#include <sys/dir.h>

typedef struct
{
	char	name[56];
	int		filepos, filelen;
} packfile_t;

typedef struct
{
	char	id[4];
	int		dirofs;
	int		dirlen;
} packheader_t;

int		packhandle;
packfile_t	*packfiles;
char	packfilename[256];
int		numpackfiles;

/*
=================
LoadPackFile
=================
*/
void LoadPackFile (char *packfile)
{
	packheader_t		header;
	int					i;
	
	packhandle = SafeOpenRead (packfile);
	SafeRead (packhandle, (void *)&header, sizeof(header));
	if (header.id[0] != 'P' || header.id[1] != 'A'
	|| header.id[2] != 'C' || header.id[3] != 'K')
		Error ("%s is not a packfile", packfile);
	header.dirofs = LittleLong (header.dirofs);
	header.dirlen = LittleLong (header.dirlen);
	
	lseek (packhandle, header.dirofs, SEEK_SET);
	packfiles = malloc (header.dirlen);
	SafeRead (packhandle, (void *)packfiles, header.dirlen);
	numpackfiles = header.dirlen / sizeof(packfile_t);
	for (i=0 ; i<numpackfiles ; i++)
	{
		packfiles[i].filepos = LittleLong(packfiles[i].filepos);
		packfiles[i].filelen = LittleLong(packfiles[i].filelen);
	}
}

void Sys_mkdir (char *path)
{
	if (mkdir (path, 0777) != -1)
		return;
	if (errno != EEXIST)
		Error ("mkdir %s: %s",path, strerror(errno)); 
}

/*
============
CreatePath
============
*/
void	CreatePath (char *path)
{
	char	*ofs;
	
	for (ofs = path+1 ; *ofs ; ofs++)
	{
		if (*ofs == '/')
		{	// create the directory
			*ofs = 0;
			Sys_mkdir (path);
			*ofs = '/';
		}
	}
}

/*
===========
CopyFile

Copies a file, creating any directories needed
===========
*/
void CopyFile (char *src, char *dest)
{
}


/*
============
main
============
*/
void main (int argc, char **argv)
{
	int		i;
	char	dest[1024];
	int		out;
	int		remaining, count;
	char	buf[4096];

	if (argc != 3)
		Error ("usage: unpack <packfile> <dirbase>\nexample: unpack id1.pak /raid/quake/id1\n");

	LoadPackFile (argv[1]);

	for (i=0 ; i<numpackfiles ; i++)
	{
		sprintf (dest, "%s/%s", argv[2], packfiles[i].name);
		lseek (packhandle, packfiles[i].filepos, SEEK_SET);
		printf ("writing %s\n", dest);
		remaining = packfiles[i].filelen;
		CreatePath (dest);
		out = SafeOpenWrite (dest);
		
		while (remaining)
		{
			if (remaining < sizeof(buf))
				count = remaining;
			else
				count = sizeof(buf);
			SafeRead (packhandle, buf, count);
			SafeWrite (out, buf, count);
			remaining -= count;
		}	
		close (out);	
	}
}

