package com.rnboat.framework.util;

import android.util.Log;

import com.blankj.utilcode.util.ShellUtils;

import java.io.File;

public class RootInstallUtil {

    private static boolean isSpace(final String s) {
        if (s == null) return true;
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    private static boolean isFileExists(final File file) {
        return file != null && file.exists();
    }

    private static boolean isDeviceRooted() {
        String su = "su";
        String[] locations = {"/system/bin/", "/system/xbin/", "/sbin/", "/system/sd/xbin/",
                "/system/bin/failsafe/", "/data/local/xbin/", "/data/local/bin/", "/data/local/"};
        for (String location : locations) {
            if (new File(location + su).exists()) {
                return true;
            }
        }
        return false;
    }

    public static boolean rootInstall(String packageName, File installFile) {
        if (isSpace(packageName)) return false;
        if (!isFileExists(installFile)) return false;
        String filePath = '"' + installFile.getAbsolutePath() + '"';

        String commandInstall = "LD_LIBRARY_PATH=/vendor/lib*:/system/lib* pm install -t -r "
                + filePath;
        String commandLaunchApp = "am start "
                + packageName + "/" + packageName + ".MainActivity";

        ShellUtils.CommandResult commandResult = ShellUtils.execCmd(commandInstall + ";" + commandLaunchApp + ";", isDeviceRooted());
        if (commandResult.successMsg != null
                && commandResult.successMsg.toLowerCase().contains("success")) {
            return true;
        } else {
            Log.e("AppUtils", "rootInstallAppSilent successMsg: " + commandResult.successMsg +
                    ", errorMsg: " + commandResult.errorMsg);
            return false;
        }
    }
}
