/*
 * Copyright (c) 2003-2005 Sendmail, Inc. and its suppliers.
 *      All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 */

#include "sm/generic.h"
SM_RCSID("@(#)$Id: ibdbrcvr.c,v 1.10 2007/06/18 04:42:31 ca Exp $")
#include "sm/error.h"
#include "sm/memops.h"
#include "sm/stat.h"
#include "sm/time.h"
#include "sm/assert.h"
#include "sm/ibdb.h"
#include "ibdb.h"

#include <stdio.h>	/* for rename() */

/*
**  IBDBRCVR_OPEN -- Prepare IBDB for recovery
**	Check whether IBDB or recovery IBDB exists.
**
**	Parameters:
**		none.
**
**	Returns:
**		>=0: which IBDB has been opened.
**		<0: usual sm_error code.
**
**	Side Effects:
**		renames IBDB directory to recovery directory if only
**		the former exists.
*/

sm_ret_T
ibdbrcvr_open(void)
{
	int r;
	char *ibdb_dir, *rcvr_dir;
	struct stat sb;

	/*
	**  Does recovery IBDB exist?
	**  If yes: previous recovery run was aborted
	*/

	IBDB_DIR(rcvr_dir, NULL, IBDB_OFL_RCVR);
	r = stat(rcvr_dir, &sb);
	if (r == 0)
		return SM_IBDB_RCVR_EXISTS;
	/* check whether it's a directory? */

	/* Does IBDB exist? If no: no recovery necessary */
	IBDB_DIR(ibdb_dir, NULL, IBDB_OFL_WRITE);
	r = stat(ibdb_dir, &sb);
	if (r < 0)
	{
		if (errno == ENOENT)
			return SM_IBDB_NO_RCVR;
		return sm_error_perm(SM_EM_IBDB, errno);
	}

	/* rename IBDB to IBDB_R and let the caller open that. */
	r = rename(ibdb_dir, rcvr_dir);
	if (r < 0)
		return sm_error_perm(SM_EM_IBDB, errno);

	return SM_SUCCESS;
}

/*
**  IDBRCVR_CLOSE -- close IBDB recovery: remove IBDB_R directory
**
**	Parameters:
**		none.
**
**	Returns:
**		usual sm_error code (from rmdir())
*/

sm_ret_T
ibdbrcvr_close(void)
{
	int r;
	char *ibdb_dir;

	IBDB_DIR(ibdb_dir, NULL, IBDB_OFL_RCVR);
	r = rmdir(ibdb_dir);
	if (r < 0)
		return sm_error_perm(SM_EM_IBDB, errno);
	return SM_SUCCESS;
}


syntax highlighted by Code2HTML, v. 0.9.1