// Package
package zeroslackr.installer;

import java.io.*;
import java.util.*;
import java.util.zip.*;
import com.ice.tar.*;

// Imports

/**
 * Abstract Tools class
 * <p>
 * Collection of useful methods.
 * <p>
 * Licensed under <A HREF="http://www.gnu.org/licenses/gpl.txt">GNU GPL (Version 3)</A>. 
 * <p>
 * @author	Keripo
 * @version	1.0 Dec 21, 2007
 */

public abstract class Tools {

	/**
	 * Returns the file extension of a String path.
	 * @param	file	String of file location.
	 * @return	File extension or "UNKNOWN" if no file extension.
	 */
	public static final String getFileStringExtension (String file) {
		if (file.lastIndexOf('.')!=-1) {
			return file.substring(file.lastIndexOf('.')+1).toUpperCase();
		} else {
			return null;
		}
	}
	
	
	public static void extract (String file, String dest) throws IOException {
		String ext = getFileStringExtension(file);
		if (ext == "GZ") {
			String ext2 = getFileStringExtension(file.substring(0, file.lastIndexOf('.')));
			if (ext2 == "TAR") {
				extractTarGz(file, dest);
			}
		}
		
	}
	
	public static void extractGz (String file, String dest) throws IOException {
		
		// Create input stream
		GZIPInputStream is = new GZIPInputStream ( new FileInputStream( new File (file) ) );
		
		// Extract
		
		
		// Cleanup
		is.close();
		
	}
	
	public static void extractTarGz (String file, String dest) throws IOException {
		
		// Create directories
		File destFolder = new File(dest);
		destFolder.mkdirs();
		
		// Create input stream
		TarInputStream is = new TarInputStream ( new GZIPInputStream ( new FileInputStream( new File (file) ) ) );
		
		// Extract
		TarEntry e;
		while ( ( e = is.getNextEntry() ) != null ) {
			// Extraction file path
			File destFile = new File ( destFolder.getPath() + File.separatorChar  + e.getName() );
			if (e.isDirectory()) { // Directory
				// Make directory
				destFile.mkdirs();
			} else { // File
				// Extract to location
				FileOutputStream out = new FileOutputStream(destFile);
				is.copyEntryContents(out);
				out.close();
			}
		}
		
		// Cleanup
		is.close();

	} // untargz
	
	
}
