/* The checkout command implementation. */
/* $Id: checkout.c,v 1.6 2003/08/01 10:06:37 pasky Exp $ */

/*
 * PaVS - Pasky's Version System, advanced version control system
 * Copyright (C) 2003  Petr Baudis
 *
 * This program 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 program 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 program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdio.h>
#include <string.h>

#include <libpavs/checkout.h>

#include "args.h"
#include "checkout.h"
#include "error.h"


/* TODO: Parameters like output or source control. */
/* TODO: Multiple files support. */


enum pa_errcode
pa_checkout (struct args *args)
{
	char *srcfile = NULL, *destdir = NULL, *revision = NULL;
	int paramstate = 0, origstate = 0;
	int ret;

	/* Eat 'checkout'. */
	args_shift (args);

	while (args->argc > 0) {
		char *param = args_shift (args);

		if ((paramstate < 2 && param[0] == '-') || paramstate == 4) {
			if (! strcmp (param, "-r")) {
				origstate = paramstate;
				paramstate = 5;
				continue;
			} else if (! strcmp (param, "-h")
				   || ! strcmp (param, "--help")) {
				pa_checkout_help ("checkout");
				return 0;
			} else if (! strcmp (param, "--")) {
				if (paramstate < 2)
					origstate = paramstate += 2;
				continue;
			} else {
				return PEARGINVAL;
			}
		}

		switch (paramstate) {
			case 0:
			case 2:
				srcfile = param;
				paramstate ++;
				break;
			case 1:
			case 3:
				destdir = param;
				paramstate = 4;
				break;
			case 4:
				return PEARGMANY;
			case 5:
				revision = param;
				paramstate = origstate;
				break;
		}
	}

	if (! srcfile) return PEARGMISSING;
	if (! destdir) destdir = ".";

	if (! srcfile [0] || ! destdir [0]) return PEARGINVAL;

	ret = pavs_checkout_file (srcfile, destdir, revision);

	return ret > 0 ? 0 : PEMISC;
}

void
pa_checkout_help (char *cmdname)
{
	printf ("Usage: pa checkout [-r REV] SRCFILE [DESTDIR]\n");
	printf ("This command checks out the specified revision (or HEAD) from SRCFILE into\n");
	printf ("an appropriate file in DESTDIR (or in the current working directory, if\n");
	printf ("unspecified).\n");
	printf ("\n");
	printf ("   -r REV       Fetch the revision REV instead of the latest one.\n");
	printf ("\n");
	printf ("Note that this command is rather for testing so far. Its usage is to be\n");
	printf ("changed dramatically in near future.\n");
}
