package jp.mobilehackerz.is01root;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.util.Log;
import android.app.Activity;

public class FileUtils {
	static public boolean fileExists(String fn) {
		return new File(fn).exists();
	}

	static public boolean chmod(String file, String mode) {
		if (android.tether.system.NativeTask.runCommand("chmod "+ mode + " " + file) == 0) {
			return true;
		}
		return false;
	}

	static public String copyFile(String filename, String permission, int resource, Activity parent) {
		String result = copyFile(filename, resource, parent);
		if (result != null) {
			return result;
		}
		if (chmod(filename, permission) != true) {
			result = "Can't change file-permission for '"+filename+"'!";
		}
		return result;
	}
    
	static public String copyFile(String filename, int resource, Activity parent) {
		File outFile = new File(filename);
		Log.d("IS01Root", "Copying file '"+filename+"' ...");
		InputStream is = parent.getResources().openRawResource(resource);
		byte buf[] = new byte[1024];
		int len;
		try {
			OutputStream out = new FileOutputStream(outFile);
			while((len = is.read(buf))>0) {
				out.write(buf,0,len);
			}
			out.close();
			is.close();
		} catch (IOException e) {
			return "Couldn't install file - "+filename+"!";
		}
		return null;
	}
}
