/*
 * e2cat.c - tool to output (think "cat") a file from a non-mounted
 *           EXT2/3/4 filesystem (from either a device or an image file)
 *
 * Required: Debian/Ubuntu -> ext2fs-dev, libgcrypt-dev
 *           RedHat/Fedora -> e2fsprogs-libs, libgcrypt-devel
 *           SuSE/OpenSuSE -> e2fsprogs-devel
 * Compile:  gcc -lext2fs -lgcrypt -o e2cat e2cat.c
 *
 * Copyright (C) 2009   Jürgen Pabel   <jpabel@akkaya.de>
 *
 * This package is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This package 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this package; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 */

#define _GNU_SOURCE
#define _BSD_SOURCE
#define _POSIX_C_SOURCE 1
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <ext2fs/ext2_fs.h>
#include <ext2fs/ext2fs.h>

int find_file(ext2_filsys e2fs, const char* filename, ext2_ino_t* e2ino) 
{
	const char* start;
	const char* end;
	int err = 0;

	*e2ino = EXT2_ROOT_INO;
	start = filename;
	if(start[0] == '/')
		start++;
	end = strchr(start, '/');
	while(err == 0 && end != NULL) {
		err = ext2fs_lookup(e2fs, *e2ino, start, (end-start), NULL, e2ino);
		start = end + 1;
		end = strchr(start, '/');
	}
	if(err == 0)
		err = ext2fs_lookup(e2fs, *e2ino, start, strlen(start), NULL, e2ino);
	return err;
}

int main(int argc, char* argv[])
{
	char buf[4096];
	size_t chunk=4096;
        ext2_filsys e2fs;
        ext2_ino_t  e2ino;
        ext2_file_t e2file;
        int err;

	if(argc != 3) {
		printf("USAGE: e2cat <DEVICE/IMAGE> <PATH_TO_FILE_ON_FILESYSTEM>\n");
		return -1;
	}
        err = ext2fs_open(argv[1], EXT2_FLAG_FORCE, 0, 0, unix_io_manager, &e2fs);
        if(err != 0) {
                printf("ERROR: could not open %s as EXT2 filesystem\n", argv[1]);
                exit(err);
        }

	err = find_file(e2fs, argv[2], &e2ino);
        if(err != 0) {
                printf("ERROR: file %s not found\n", argv[2]);
                exit(err);
        }
	err = ext2fs_file_open(e2fs, e2ino, 0, &e2file);
	while(err == 0 && chunk > 0) {
		err = ext2fs_file_read(e2file, buf, 4096, &chunk);
		if(err == 0)
			write(STDOUT_FILENO, buf, chunk);
	}
	if(err == 0)
		err = ext2fs_file_close(e2file);
	ext2fs_close(e2fs);
	return err;
}

