/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

package com.sun.enterprise.config.backup;

import com.sun.enterprise.config.backup.util.*;
import java.io.*;
import java.util.*;


/**
 *
 * @author  Byron Nevins
 */


public class BackupManager extends BackupRestoreManager
{
	public BackupManager(BackupRequest req) throws BackupException
	{
		super(req);
	}
	
	///////////////////////////////////////////////////////////////////////////////

	public final String backup() throws BackupException
	{
		String mesg = StringHelper.get("backup-res.SuccessfulBackup");
		String statusString = writeStatus();
		
		if(request.terse == false)
		{
			mesg += "\n\n" + statusString;
		}
		
		try
		{
			ZipStorage zs = new ZipStorage(request);
			zs.store();
			return mesg;
		}
		finally
		{
			status.delete();
			FileUtils.protect(request.backupFile);
		}
	}
	
	///////////////////////////////////////////////////////////////////////////////

	void init() throws BackupException
	{
		super.init();
		
		if(request.backupFile != null)
			throw new BackupException("backup-res.InternalError", "No backupFilename may be specified for a backup -- it is reserved for restore operations only.");
		
		if(!FileUtils.safeIsDirectory(request.domainDir))
			throw new BackupException("backup-res.NoDomainDir", request.domainDir);

		File backupDir = new File(request.domainDir, Constants.BACKUP_DIR);

		// not an error for this directory to not exist yet
		backupDir.mkdirs();

		// NOW it's an error to not exist...
		if(!FileUtils.safeIsDirectory(backupDir))
			throw new BackupException("backup-res.NoBackupDirCantCreate", backupDir);

		String ts = "" + request.timestamp + ".zip";
		BackupFilenameManager bfmgr = new BackupFilenameManager(backupDir);
		request.backupFile = bfmgr.next();
		//request.backupFile = new File(backupDir, ts);
	}
	
	///////////////////////////////////////////////////////////////////////////////
	
	private String writeStatus()
	{
		status = new Status();
		return status.write(request);
	}
	
	///////////////////////////////////////////////////////////////////////////////

	Status status;
}
