package jp.mobilehackerz.is01root;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.appwidget.AppWidgetManager;
import android.content.*;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class IS01root extends Activity implements Runnable {
	private ProgressDialog progressDialog; 
	private int mode;

	// -----------------------------
	//   Actions
	// -----------------------------
	static public int DoEnableSu() {
		return android.tether.system.NativeTask.runCommand("/sqlite_journals/is01root/su -c \"mv /sbin/su0 /sbin/su\"");
	}
	static public int DoDisableSu() {
		return android.tether.system.NativeTask.runCommand("/sqlite_journals/is01root/su -c \"mv /sbin/su /sbin/su0\"");
	}
	static public int DoBootSh() {
		return android.tether.system.NativeTask.runCommand("/sqlite_journals/is01root/su -c \"/sqlite_journals/is01root/boot.sh\"");
	}
	static public int DoUnInstall() {
		return android.tether.system.NativeTask.runCommand("/sqlite_journals/is01root/su -c \"/sh_tmp/uninstall.sh\"");
	}
	static public int DoGetRoot() {
		return android.tether.system.NativeTask.runCommand("/system/bin/sh /sh_tmp/getroot.sh");
	}


	// -----------------------------
	//   Status
	// -----------------------------
	static public boolean isSuInstalledAndDisabled() {
		return FileUtils.fileExists("/sbin/su0");
	}

	static public boolean isSuInstalledAndEnabled() {
		return FileUtils.fileExists("/sbin/su");
	}

	static public boolean isSuInstalled() {
		return FileUtils.fileExists("/sqlite_journals/is01root/su");
	}

	static public boolean isRooted() {
		if (android.tether.system.NativeTask.runCommand("/system/bin/sh /sh_tmp/roottest.sh") == 0) {
			return false;
		} else {
			return true;
		}
	}

	// -----------------------------
	//   ウィジェットの表示を更新
	// -----------------------------
	private void UpdateWidget() {
		// 表示更新
		RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.widget);
		int imgid;
		if (IS01root.isSuInstalledAndDisabled()) {
			imgid = R.drawable.widget_off;
		} else if (IS01root.isSuInstalledAndEnabled()) {
			imgid = R.drawable.widget_on;
		} else if (IS01root.isSuInstalled()) {
			imgid = R.drawable.widget_middle;
		} else {
			imgid = R.drawable.widget_blank;
		}
		remoteViews.setImageViewResource(R.id.ImageView01, imgid);
		//
		ComponentName thisWidget = new ComponentName(this, RootSwitchWidgetProvider.class);
		AppWidgetManager manager = AppWidgetManager.getInstance(this);
		manager.updateAppWidget(thisWidget, remoteViews);
	}

	// -----------------------------
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mode = 0;

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		TextView	dsc		= (TextView)this.findViewById(R.id.TextView01);
		dsc.setText(R.string.Description);

		Button		btn		= (Button) this.findViewById(R.id.Button01);  
		TextView	tv		= (TextView) this.findViewById(R.id.HelloText);

		Button		btn2	= new Button(this);
		btn2.setText(R.string.Button02);
		btn2.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) { ViewLicense(); }
		});

		// -----------------------------------
		//   状況チェック
		// -----------------------------------
		if (isSuInstalledAndDisabled()) {
			mode = 4;
		} else if (isSuInstalledAndEnabled()) {
			mode = 3;
		} else if (isSuInstalled()) {
			// suが既にインストールされている
			mode = 2;
		} else {
			// rageagainstthecageのコピー
			FileUtils.copyFile("/sh_tmp/rageagainstthecage", "0755", R.raw.rageagainstthecage, this);
			// busyboxのコピー
			FileUtils.copyFile("/sh_tmp/busybox", "0755", R.raw.busybox, this);
			// suのコピー
			FileUtils.copyFile("/sh_tmp/su", "0666", R.raw.su, this);
			// getroot.shのコピー
			FileUtils.copyFile("/sh_tmp/getroot.sh", "0755", R.raw.getroot, this);
			// roottest.shのコピー
			FileUtils.copyFile("/sh_tmp/roottest.sh", "0755", R.raw.roottest, this);
			// boot.shのコピー
			FileUtils.copyFile("/sh_tmp/boot.sh", "0755", R.raw.boot, this);
			// sysremount.shのコピー
			FileUtils.copyFile("/sh_tmp/sysremount_atmyownrisk.sh", "0755", R.raw.sysremount, this);

			// autoexec.shのコピー
			FileUtils.copyFile("/sh_tmp/autoexec.sh", "0755", R.raw.autoexec, this);
			// _suのコピー
			FileUtils.copyFile("/sh_tmp/_su", "0755", R.raw.su_, this);
			// libril-wrapper.soのコピー
			FileUtils.copyFile("/sh_tmp/libril-wrapper.so", "0644", R.raw.libril_wrapper, this);
			// msm_nand_ex.koのコピー
			FileUtils.copyFile("/sh_tmp/msm_nand_ex.ko", "0644", R.raw.msm_nand_ex, this);
			// local.propのコピー
			FileUtils.copyFile("/sh_tmp/local.prop", "0644", R.raw.local, this);
			
			
			// root取れてる？
			if (isRooted()) {
				// SuperUser
				mode = 1;
			} else {
				// User
				mode = 0;
			}
		}

		// -----------------------------------
		//   動作モードに応じて画面をつくる
		// -----------------------------------
		Button btn3 = new Button(this);
		btn3.setText(R.string.ButtonStep5);
		btn3.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) { Uninstall(); }
		});
		LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout01);
		//
		switch(mode) {
		case 0:
			tv.setText(R.string.DescStep1);
			btn.setText(R.string.ButtonStep1);
			btn.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) { RunRageCage(); }
			});
			layout.addView(btn2);
			break;

		case 1:
			tv.setText(R.string.DescStep2);
			btn.setText(R.string.ButtonStep2);
			btn.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) { InstallSu(); }
			});
			break;

		case 2:
			tv.setText(R.string.DescStep3);
			btn.setText(R.string.ButtonStep3);
			btn.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) { CopySystem_start(); }
			});
			layout.addView(btn3);
			break;

		case 3:
			tv.setText(R.string.DescStep4a);
			btn.setText(R.string.ButtonStep4a);
			btn.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) { DoDisableSu(); UpdateWidget(); finish(); }
			});
			//
			layout.addView(btn3);
			break;
		
		default:
			tv.setText(R.string.DescStep4b);
			btn.setText(R.string.ButtonStep4b);
			btn.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) { DoEnableSu(); UpdateWidget(); finish(); }
			});
			//
			layout.addView(btn3);
			break;
		}
	}

	private void RunRageCage(){
		AlertDialog.Builder AlertDlgBldr = new AlertDialog.Builder(IS01root.this);
		AlertDlgBldr.setTitle(R.string.Warning);
		AlertDlgBldr.setMessage(R.string.RunRageCage);
		AlertDlgBldr.setPositiveButton(R.string.Start, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				RageCage_start();
			}
		});
		AlertDlgBldr.setNegativeButton(R.string.Abort, null );
		AlertDialog AlertDlg = AlertDlgBldr.create();
		AlertDlg.show();
	}

	private void InstallSu(){
		AlertDialog.Builder AlertDlgBldr = new AlertDialog.Builder(IS01root.this);
		AlertDlgBldr.setTitle(R.string.Confirm);
		AlertDlgBldr.setMessage(R.string.RunInstall);
		AlertDlgBldr.setPositiveButton(R.string.Start, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				InstallSu_start();
			}
		});
		AlertDlgBldr.setNegativeButton(R.string.Abort, null );
		AlertDialog AlertDlg = AlertDlgBldr.create();
		AlertDlg.show();
	}

	private void Uninstall(){
		AlertDialog.Builder AlertDlgBldr = new AlertDialog.Builder(IS01root.this);
		AlertDlgBldr.setTitle(R.string.Confirm);
		AlertDlgBldr.setMessage(R.string.RunUninstall);
		AlertDlgBldr.setPositiveButton(R.string.Start, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Uninstall_start();
			}
		});
		AlertDlgBldr.setNegativeButton(R.string.Abort, null );
		AlertDialog AlertDlg = AlertDlgBldr.create();
		AlertDlg.show();
	}

	private void PleaseReboot(String str){
		AlertDialog.Builder AlertDlgBldr = new AlertDialog.Builder(IS01root.this);
		AlertDlgBldr.setTitle(R.string.Confirm);
		AlertDlgBldr.setMessage(str);
		AlertDlgBldr.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				PleaseReboot_OK();
			}
		});
		AlertDialog AlertDlg = AlertDlgBldr.create();
		AlertDlg.show();
	}
	
	private void PleaseReboot_OK(){
		finish();
	}

	private void RageCage_start(){
		progressDialog = new ProgressDialog(this);
		progressDialog.setTitle(R.string.GetRoot);
		progressDialog.setMessage(getString(R.string.WaitAmoment));
		progressDialog.setIndeterminate(false);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.show();
	  
		Thread thread = new Thread(this);
		thread.start();
	}

	private void InstallSu_start(){
		progressDialog = new ProgressDialog(this);
		progressDialog.setTitle(R.string.GetSu);
		progressDialog.setMessage(getString(R.string.WaitAmoment));
		progressDialog.setIndeterminate(false);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.show();
	  
		Thread thread = new Thread(this);
		thread.start();
	}

	private void Uninstall_start(){
		// uninstall.shのコピー
		FileUtils.copyFile("/sh_tmp/uninstall.sh", "0755", R.raw.uninstall, this);
		//
		progressDialog = new ProgressDialog(this);
		progressDialog.setTitle(R.string.UninstallSu);
		progressDialog.setMessage(getString(R.string.WaitAmoment));
		progressDialog.setIndeterminate(false);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.show();
	  
		Thread thread = new Thread(this);
		thread.start();
	}

	private void CopySystem_start(){
		progressDialog = new ProgressDialog(this);
		progressDialog.setTitle(R.string.CopySu);
		progressDialog.setMessage(getString(R.string.WaitAmoment));
		progressDialog.setIndeterminate(false);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.show();
	  
		Thread thread = new Thread(this);
		thread.start();
	}

	public void run() {  
		boolean abort = false;
		int time;

		try{  
	    	// run getroot.sh
			switch(mode) {
			case 0:
				// SuperUserを獲りに行く
				if (DoGetRoot() != 0) {
					abort = true;
				}
				break;
			case 1:
				// 必要ファイルをコピーする
				if (DoGetRoot() != 0) {
					abort = true;
				}
				break;
			case 2:
				// 起動後設定
				if (DoBootSh() != 0) {
					abort = true;
				}
				break;
			default:
				// アンインストール
				if (DoUnInstall() != 0) {
					abort = true;
				}
				break;
			}

			// root取得待ち
			time = 0;
			while(abort == false) {
		    	Thread.sleep(1000); // 1秒スリープ  
		    	if (mode == 0) {
		    		if (isRooted()) { abort = true; }
		    	} else {
		    		if (isSuInstalled()) { abort = true; }
		    	}
		    	time++;
		    	if (time>30) { abort = true; }
			}
		} catch (InterruptedException ie){
		}
		handler.sendEmptyMessage(0);
	}  

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			// プログレスダイアログ終了  
			progressDialog.dismiss();  

			UpdateWidget();
			if (mode == 0) {
				// Install su
				InstallSu();
//				PleaseReboot(getString(R.string.EndRooted));
			} else if (mode == 1) {
				// Reboot or Retry
				if (isSuInstalled()) {
					PleaseReboot(getString(R.string.EndInstall));
				} else {
					PleaseReboot(getString(R.string.EndInstallBad));
				}
			} else {
				finish();
			}
			
		}
	};

	private void ViewLicense(){
		AlertDialog.Builder AlertDlgBldr = new AlertDialog.Builder(IS01root.this);
		AlertDlgBldr.setTitle("License");
		AlertDlgBldr.setMessage("このアプリケーションはGNU General Public License v3 (http://www.gnu.org/licenses/gpl.html) によって提供されています。内部にはrageagainstthecage、仙石浩明版su、goroh_kunによるIS01 hack、busybox for androidのバイナリが含まれており、これらはそれぞれのライセンスのもとに提供されています。詳しくは http://mobilehackerz.jp/Software/Android/IS01root をご参照ください。");
		AlertDlgBldr.setPositiveButton("OK", null);
		AlertDialog AlertDlg = AlertDlgBldr.create();
		AlertDlg.show();
	}

}
