/*
  fix.c -- fix ROM sets
  Copyright (C) 1999-2007 Dieter Baron and Thomas Klausner

  This file is part of ckmame, a program to check rom sets for MAME.
  The authors can be contacted at <ckmame@nih.at>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:
  1. Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in
     the documentation and/or other materials provided with the
     distribution.
  3. The name of the author may not be used to endorse or promote
     products derived from this software without specific prior
     written permission.
 
  THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/



#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <zip.h>

#include "archive.h"
#include "error.h"
#include "file_location.h"
#include "funcs.h"
#include "game.h"
#include "garbage.h"
#include "globals.h"
#include "match.h"
#include "pri.h"
#include "types.h"
#include "util.h"
#include "xmalloc.h"

static int fix_disks(game_t *, images_t *, result_t *);
static int fix_files(game_t *, archive_t *, result_t *, garbage_t *);



int
fix_game(game_t *g, archive_t *a, images_t *im, result_t *res)
{
    int i;
    bool move;
    garbage_t *gb;

    if (fix_options & FIX_DO) {
	gb = garbage_new(a);
	
	if (archive_ensure_zip(a) < 0) {
	    char *new_name;

	    /* opening the zip file failed, rename it and create new one */

	    if ((new_name=make_unique_name("broken", "%s",
					   archive_name(a))) == NULL)
		return -1;

	    if (fix_options & FIX_PRINT)
		printf("%s: rename broken zip to `%s'\n",
		       archive_name(a), new_name);
	    if (rename_or_move(archive_name(a), new_name) < 0) {
		free(new_name);
		return -1;
	    }
	    free(new_name);
	    if (archive_ensure_zip(a) < 0)
		return -1;
	}

	if (extra_delete_list)
	    delete_list_mark(extra_delete_list);
	if (needed_delete_list)
	    delete_list_mark(needed_delete_list);
	if (superfluous_delete_list)
	    delete_list_mark(superfluous_delete_list);
    }

    for (i=0; i<archive_num_files(a); i++) {
	switch (result_file(res, i)) {
	case FS_UNKNOWN:
	    if (fix_options & FIX_IGNORE_UNKNOWN)
		break;
	    move = (fix_options & FIX_MOVE_UNKNOWN);
	    if (fix_options & FIX_PRINT)
		printf("%s: %s unknown file `%s'\n",
		       archive_name(a),
		       (move ? "mv" : "delete"),
		       file_name(archive_file(a, i)));

	    if (move)
		garbage_add(gb, i, false);
	    else
		archive_file_delete(a, i);
	    break;

	case FS_DUPLICATE:
	    if (!(fix_options & FIX_DELETE_DUPLICATE))
		break;
	    /* fallthrough */
	case FS_SUPERFLUOUS:
	    if (fix_options & FIX_PRINT)
		printf("%s: delete %s file `%s'\n",
		       archive_name(a),
		       (result_file(res, i) == FS_SUPERFLUOUS
			? "unused" : "duplicate"),
		       file_name(archive_file(a, i)));

	    /* XXX: handle error (how?) */
	    archive_file_delete(a, i);
	    break;

	case FS_NEEDED:
	    if (fix_options & FIX_PRINT)
		printf("%s: save needed file `%s'\n",
		       archive_name(a),
		       file_name(archive_file(a, i)));

	    /* XXX: handle error (how?) */
	    save_needed(a, i, fix_options & FIX_DO);
	    break;

	case FS_BROKEN:
	case FS_USED:
	case FS_MISSING:
	case FS_PARTUSED:
	    /* nothing to be done */
	    break;
	}
    }

    fix_files(g, a, res, gb);

    if (fix_options & FIX_DO) {
	if (garbage_close(gb) < 0) {
	    /* XXX: handle error (how?) */
	    archive_rollback(a);
	    /* XXX: return -1 here? */
	}
    }

    if (fix_options & FIX_PRINT) {
	if ((a->flags & ARCHIVE_FL_TORRENTZIP) && !archive_is_torrentzipped(a))
	    printf("%s: torrentzipping\n", archive_name(a));
    }

    if (archive_commit(a) < 0) {
	if ((fix_options & FIX_DO) && extra_delete_list)
	    delete_list_rollback(extra_delete_list);
	if ((fix_options & FIX_DO) && needed_delete_list)
	    delete_list_rollback(needed_delete_list);
	if ((fix_options & FIX_DO) && superfluous_delete_list)
	    delete_list_rollback(superfluous_delete_list);
    }

    fix_disks(g, im, res);

    return 0;
}



static int
fix_disks(game_t *g, images_t *im, result_t *res)
{
    int i;
    disk_t *d;
    match_disk_t *md;
    const char *name;
    char *fname;
    bool do_copy;
    
    for (i=0; i<game_num_disks(g); i++) {
	d = game_disk(g, i);
	name = images_name(im, i);
	
	switch (result_image(res, i)) {
	case FS_UNKNOWN:
	case FS_BROKEN:
	    if (fix_options & FIX_PRINT)
		printf("%s: %s unknown image\n",
		       name,
		       ((fix_options & FIX_MOVE_UNKNOWN) ? "mv" : "delete"));
	    if (fix_options & FIX_DO) {
		if (fix_options & FIX_MOVE_UNKNOWN)
		    move_image_to_garbage(name);
		else
		    my_remove(name);
	    }
	    break;

	case FS_DUPLICATE:
	case FS_SUPERFLUOUS:
	    if (fix_options & FIX_PRINT)
		printf("%s: delete %s image\n",
		       name,
		       (result_image(res, i) == FS_SUPERFLUOUS
			? "unused" : "duplicate"));
	    if (fix_options & FIX_DO)
		my_remove(name);
	    remove_from_superfluous(name);
	    break;

	case FS_NEEDED:
	    if (fix_options & FIX_PRINT)
		printf("%s: save needed image\n", name);
	    save_needed_disk(name, (fix_options & FIX_DO));
	    break;

	case FS_MISSING:
	case FS_USED:
	case FS_PARTUSED:
	    break;
	}
    }
    
    for (i=0; i<game_num_disks(g); i++) {
	d = game_disk(g, i);
	md = result_disk(res, i);

	switch (match_disk_quality(md)) {
	case QU_COPIED:
	    if ((name=findfile(disk_name(d), TYPE_DISK)) != NULL) {
		/* XXX: move to garbage */
	    }
	    else
		fname = make_file_name(TYPE_DISK, 0, disk_name(d));

	    do_copy = ((fix_options & FIX_DELETE_EXTRA) == 0
		       && match_disk_where(md) == FILE_EXTRA);
    
	    if (fix_options & FIX_PRINT)
		printf("%s `%s' to `%s'\n",
		       do_copy ? "copy" : "rename",
		       match_disk_name(md), fname);
	    if (fix_options & FIX_DO) {
		if (do_copy)
		    link_or_copy(match_disk_name(md), fname);
		else
		    rename_or_move(match_disk_name(md), fname);
	    }
	    remove_from_superfluous(match_disk_name(md));
	    
	    free(fname);
	    break;

	case QU_HASHERR:
	    /* XXX: move to garbage */
	    break;

	default:
	    /* no fix necessary/possible */
	    break;
	}
    }

    return 0;
}



static int
fix_files(game_t *g, archive_t *a, result_t *res, garbage_t *gb)
{
    archive_t *afrom;
    match_t *m;
    file_t *r;
    int i;

    seterrinfo(NULL, archive_name(a));

    for (i=0; i<game_num_files(g, file_type); i++) {
	m = result_rom(res, i);
	if (match_source_is_old(m))
	    afrom = NULL;
	else
	    afrom = match_archive(m);
	r = game_file(g, file_type, i);
	seterrinfo(file_name(r), archive_name(a));

	switch (match_quality(m)) {
	case QU_MISSING:
	    if (file_size(r) == 0) {
		/* create missing empty file */
		if (fix_options & FIX_PRINT)
		    printf("%s: create empty file `%s'\n",
			   archive_name(a), file_name(r));

		/* XXX: handle error (how?) */
		archive_file_add_empty(a, file_name(r));
	    }
	    break;
	    
	case QU_HASHERR:
	    /* all is lost */
	    break;

	case QU_LONG:
	    if (a == afrom && (fix_options & FIX_MOVE_LONG)) {
		if (fix_options & FIX_PRINT)
		    printf("%s: mv long file `%s'\n",
			   archive_name(afrom),
			   file_name(archive_file(afrom, match_index(m))));
		if (garbage_add(gb, match_index(m), true) < 0)
		    break;
	    }
	    
	    if (fix_options & FIX_PRINT)
		printf("%s: extract (offset %" PRIdoff ", size %" PRIu64
		       ") from `%s' to `%s'\n", archive_name(a),
		       PRIoff_cast match_offset(m), file_size(r),
		       file_name(archive_file(afrom, match_index(m))),
		       file_name(r));

	    if (archive_file_copy_part(afrom, match_index(m), a, file_name(r),
		    		       match_offset(m), file_size(r)) < 0)
		break;

#if 0
	    if (a == afrom) {
		if (!(fix_options & FIX_MOVE_LONG) && (fix_options & FIX_PRINT))
		    printf("%s: delete long file `%s'\n",
			   archive_name(a), file_name(r));
		archive_file_delete(a, i);
	    }
#endif
	    break;

	case QU_NAMEERR:
	    if (fix_options & FIX_PRINT)
		printf("%s: rename `%s' to `%s'\n", archive_name(a),
		       file_name(archive_file(a, match_index(m))),
		       file_name(r));

	    /* XXX: handle errors (how?) */
	    archive_file_rename(a, match_index(m), file_name(r));
	    break;

	case QU_COPIED:
	    if (fix_options & FIX_PRINT)
		printf("%s: add `%s/%s' as `%s'\n",
		       archive_name(a), archive_name(afrom),
		       file_name(archive_file(afrom, match_index(m))),
		       file_name(r));
	    
#if 0
	    /* XXX: is this neccessary? */
	    /* make room for new file, if necessary */
	    idx = archive_file_index_by_name(a, file_name(r));
	    if (idx >= 0) {
		if (file_status(archive_file(a, idx)) == STATUS_BADDUMP)
		    zip_delete(zto, idx);
		else
		    idx = -1;
	    }
#endif
	    if (archive_file_copy(afrom, match_index(m), a, file_name(r)) < 0) {
		    /* XXX: handle error (how?) */
	    }
	    else {
		if (match_where(m) == FILE_NEEDED)
		    delete_list_add(needed_delete_list,
				    archive_name(afrom), match_index(m));
		else if (match_where(m) == FILE_SUPERFLUOUS)
		    delete_list_add(superfluous_delete_list,
				    archive_name(afrom), match_index(m));
		else if (match_where(m) == FILE_EXTRA
			 && (fix_options & FIX_DELETE_EXTRA))
		    delete_list_add(extra_delete_list,
				    archive_name(afrom), match_index(m));
	    }
	    break;

	case QU_INZIP:
	    /* ancestor must copy it first */
	    break;

	case QU_OK:
	    /* all is well */
	    break;

	case QU_NOHASH:
	    /* only used for disks */
	    break;

	case QU_OLD:
	    /* nothing to be done */
	    break;
	}
    }

    return 0;
}
