public final class CMDProcessor {
    private static final String TAG = "CMDProcessor";

    public CMDProcessor() {

    }

    /* Run a system command with full redirection */
    public static ChildProcess startSysCmd(String[] cmdarray, String childStdin) {
        return new ChildProcess(cmdarray, childStdin);
    }

    public static CommandResult runSysCmd(String[] cmdarray, String childStdin) {
        ChildProcess proc = startSysCmd(cmdarray, childStdin);
        proc.waitFinished();
        return proc.getResult();
    }

    public static ChildProcess startShellCommand(String cmd) {
        String[] cmdarray = new String[3];
        cmdarray[0] = "sh";
        cmdarray[1] = "-c";
        cmdarray[2] = cmd;
        return startSysCmd(cmdarray, null);
    }

    public static CommandResult runShellCommand(String cmd) {
        ChildProcess proc = startShellCommand(cmd);
        proc.waitFinished();
        return proc.getResult();
    }

    public static ChildProcess startSuCommand(String cmd) {
        String[] cmdarray = new String[3];
        cmdarray[0] = "su";
        cmdarray[1] = "-c";
        cmdarray[2] = cmd;
        return startSysCmd(cmdarray, null);
    }

    public static CommandResult runSuCommand(String cmd) {
        ChildProcess proc = startSuCommand(cmd);
        proc.waitFinished();
        return proc.getResult();
    }

    public static boolean canSU() {
        CommandResult r = runShellCommand("id");
        StringBuilder out = new StringBuilder(0);
        out.append(r.getStdout());
        out.append(" ; ");
        out.append(r.getStderr());
        Log.d(TAG, "canSU() su[" + r.getExitValue() + "]: " + out);
        return r.success();
    }
}
 public class CPUHelper {

    private static final String TAG = "CPUHelper";
    private static BufferedReader br;

    /**
     * Checks device for SuperUser permission
     *
     * @return If SU was granted or denied
     */
    public static boolean checkSu() {
        if (!new File("/system/bin/su").exists()
                && !new File("/system/xbin/su").exists()) {
            Log.e(TAG, "su does not exist!!!");
            return false; // tell caller to bail...
        }

        try {
            new CMDProcessor();
            CommandResult commandResult = CMDProcessor.runSuCommand("ls /data/app-private");
            if (commandResult.success()) {
                Log.i(TAG, " SU exists and we have permission");
                return true;
            } else {
                Log.i(TAG, " SU exists but we dont have permission");
                return false;
            }
        } catch (final NullPointerException e) {
            Log.e(TAG, e.getLocalizedMessage().toString());
            return false;
        }
    }

    /**
     * Checks device for network connectivity
     *
     * @return If the device has data connectivity
     */
    public static boolean isNetworkAvailable(final Context c) {
        boolean state = false;
        if (c != null) {
            ConnectivityManager cm = (ConnectivityManager) c
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnected()) {
                Log.i(TAG, "The device currently has data connectivity");
                state = true;
            } else {
                Log.i(TAG, "The device does not currently have data connectivity");
                state = false;
            }
        }
        return state;
    }

    /**
     * Checks to see if Busybox is installed in "/system/"
     *
     * @return If busybox exists
     */
    public static boolean checkBusybox() {
        if (!new File("/system/bin/busybox").exists()
                && !new File("/system/xbin/busybox").exists()) {
            Log.e(TAG, "Busybox not in xbin or bin!");
            return false;
        }

        try {
            new CMDProcessor();
            if (!CMDProcessor.runSuCommand("busybox mount").success()) {
                Log.e(TAG, " Busybox is there but it is borked! ");
                return false;
            }
        } catch (final NullPointerException e) {
            Log.e(TAG, e.getLocalizedMessage().toString());
            return false;
        }
        return true;
    }

    public static String[] getMounts(final String path) {
        try {
            br = new BufferedReader(new FileReader("/proc/mounts"), 256);
            String line = null;
            while ((line = br.readLine()) != null) {
                if (line.contains(path)) {
                    return line.split(" ");
                }
            }
            br.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, "/proc/mounts does not exist");
        } catch (IOException e) {
            Log.d(TAG, "Error reading /proc/mounts");
        }
        return null;
    }

    public static boolean getMount(final String mount) {
        new CMDProcessor();
        final String mounts[] = getMounts("/system");
        if (mounts != null
                && mounts.length >= 3) {
            final String device = mounts[0];
            final String path = mounts[1];
            final String point = mounts[2];
            if (CMDProcessor.runSuCommand(
                    "mount -o " + mount + ",remount -t " + point + " " + device + " " + path)
                    .success()) {
                return true;
            }
        }
        return (CMDProcessor.runSuCommand("busybox mount -o remount," + mount + " /system").success());
    }

    public static String readOneLine(String fname) {
        BufferedReader br;
        String line = null;
        try {
            br = new BufferedReader(new FileReader(fname), 512);
            try {
                line = br.readLine();
            } finally {
                br.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "IO Exception when reading sys file", e);
            // attempt to do magic!
            return readFileViaShell(fname, true);
        }
        return line;
    }

    public static String readOneLineNotRoot(String fname) {
        if (new File(fname).exists()) {
            BufferedReader br;
            String line = null;
            try {
                br = new BufferedReader(new FileReader(fname), 512);
                try {
                    line = br.readLine();
                } finally {
                    br.close();
                }
            } catch (Exception e) {
                Log.e(TAG, "IO Exception when reading sys file", e);
                // attempt to do magic!
                return readFileViaShell(fname, false);
            }
            return line;

        } else {
            return "";
        }
    }

    public static String readFileViaShell(String filePath, boolean useSu) {
        CommandResult cr;
        if (useSu) {
            new CMDProcessor();
            cr = CMDProcessor.runSuCommand("cat " + filePath);
        } else {
            new CMDProcessor();
            cr = CMDProcessor.runShellCommand("cat " + filePath);
        }
        if (cr.success())
            return cr.getStdout();
        return null;
    }

    public static boolean writeOneLine(String fname, String value) {
        try {
            FileWriter fw = new FileWriter(fname);
            try {
                fw.write(value);
            } finally {
                fw.close();
            }
        } catch (IOException e) {
            String Error = "Error writing to " + fname + ". Exception: ";
            Log.e(TAG, Error, e);
            return false;
        }
        return true;
    }

    public static ArrayList<String> getAvailableIOSchedulers() {
        ArrayList<String> schedulers = new ArrayList<String>();
        String[] aux = readStringArray("/sys/block/mmcblk0/queue/scheduler");
        if (aux != null) {
            for (int i = 0; i < aux.length; i++) {
                if (aux[i].charAt(0) == '[') {
                    schedulers.add(i, aux[i].substring(1, aux[i].length() - 1));
                } else {
                    schedulers.add(i, aux[i]);
                }
            }
        }
        return schedulers;
    }

    public static ArrayList<String> getAvailableIOSchedulersSD() {
        ArrayList<String> schedulers = new ArrayList<String>();
        String[] aux = readStringArray("/sys/block/mmcblk1/queue/scheduler");
        if (aux != null) {
            for (int i = 0; i < aux.length; i++) {
                if (aux[i].charAt(0) == '[') {
                    schedulers.add(i, aux[i].substring(1, aux[i].length() - 1));
                } else {
                    schedulers.add(i, aux[i]);
                }
            }
        }
        return schedulers;
    }

    public static String getIOScheduler() {
        String scheduler = null;
        String[] schedulers = readStringArray("/sys/block/mmcblk0/queue/scheduler");
        if (schedulers != null) {
            for (String s : schedulers) {
                if (s.charAt(0) == '[') {
                    scheduler = s.substring(1, s.length() - 1);
                    break;
                }
            }
        }
        return scheduler;
    }

    public static String getIOSchedulerSD() {
        String scheduler = null;
        String[] schedulers = readStringArray("/sys/block/mmcblk1/queue/scheduler");
        if (schedulers != null) {
            for (String s : schedulers) {
                if (s.charAt(0) == '[') {
                    scheduler = s.substring(1, s.length() - 1);
                    break;
                }
            }
        }
        return scheduler;
    }

    private static String[] readStringArray(String fname) {
        String line = readOneLine(fname);
        if (line != null) {
            return line.split(" ");
        }
        return null;
    }

    /**
     * Long toast message
     *
     * @param c   Application Context
     * @param msg Message to send
     */
    public static void msgLong(final Context c, final String msg) {
        if (c != null && msg != null) {
            Toast.makeText(c, msg.trim(), Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Short toast message
     *
     * @param c   Application Context
     * @param msg Message to send
     */
    public static void msgShort(final Context c, final String msg) {
        if (c != null && msg != null) {
            Toast.makeText(c, msg.trim(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * Long toast message
     *
     * @param c   Application Context
     * @param msg Message to send
     */
    public static void sendMsg(final Context c, final String msg) {
        if (c != null && msg != null) {
            msgLong(c, msg);
        }
    }

    /**
     * Return a timestamp
     *
     * @param context Application Context
     */
    public static String getTimestamp(final Context context) {
        String timestamp;
        timestamp = "unknown";
        Date now = new Date();
        java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context);
        java.text.DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(context);
        if (dateFormat != null && timeFormat != null) {
            timestamp = dateFormat.format(now) + " " + timeFormat.format(now);
        }
        return timestamp;
    }

    public static boolean isPackageInstalled(final String packageName,
                                             final PackageManager pm) {
        String mVersion;
        try {
            mVersion = pm.getPackageInfo(packageName, 0).versionName;
            if (mVersion.equals(null)) {
                return false;
            }
        } catch (NameNotFoundException e) {
            return false;
        }
        return true;
    }

    public static void restartSystemUI() {
        new CMDProcessor();
        CMDProcessor.runSuCommand("pkill -TERM -f com.android.systemui");
    }

    public static void setSystemProp(String prop, String val) {
        new CMDProcessor();
        CMDProcessor.runSuCommand("setprop " + prop + " " + val);
    }

    public static String getSystemProp(String prop, String def) {
        String result = getSystemProp(prop);
        return result == null ? def : result;
    }

    private static String getSystemProp(String prop) {
        new CMDProcessor();
        CommandResult cr = CMDProcessor.runShellCommand("getprop " + prop);
        if (cr.success()) {
            return cr.getStdout();
        } else {
            return null;
        }
    }

    public class asyncReadOneLine extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... params) {
            String fname = params[0];
            BufferedReader br;
            String line = null;
            try {
                br = new BufferedReader(new FileReader(fname), 512);
                try {
                    line = br.readLine();
                } finally {
                    br.close();
                }
            } catch (Exception e) {
                Log.e(TAG, "IO Exception when reading sys file", e);
                // attempt to do magic!
                return readFileViaShell(fname, false);
            }
            return line;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        }

    }

    public static String[] getAvailableCPUFreqs() {
        String[] availableFrequencies = new String[0];
        String availableFrequenciesLine;

        if (Helpers.doesFileExist(CPUInterface.STEPS)) {
            availableFrequenciesLine = CPUHelper.readOneLineNotRoot(CPUInterface.STEPS);

            if (availableFrequenciesLine != null) {
                availableFrequencies = availableFrequenciesLine.split(" ");
                Arrays.sort(availableFrequencies, new Comparator<String>() {
                    @Override
                    public int compare(String object1, String object2) {
                        return Integer.valueOf(object1).compareTo(
                                Integer.valueOf(object2));
                    }
                });
            }
        }
        return availableFrequencies;
    }

    public static String[] getAvailableGPUFreqs() {
        String[] availableFrequencies = new String[0];
        String availableFrequenciesLine;

        if (Helpers.doesFileExist(GPUInterface.availableFreqs)) {
            availableFrequenciesLine = CPUHelper.readOneLineNotRoot(GPUInterface.availableFreqs);

            if (availableFrequenciesLine != null) {
                availableFrequencies = availableFrequenciesLine.split(" ");
                Arrays.sort(availableFrequencies, new Comparator<String>() {
                    @Override
                    public int compare(String object1, String object2) {
                        return Integer.valueOf(object1).compareTo(
                                Integer.valueOf(object2));
                    }
                });
            }
        }
        return availableFrequencies;
    }
}
 public class Helpers {

    private static final String BUILD_PROP = "/system/build.prop";
    // don't show unavoidable warnings
    @SuppressWarnings({
            "UnusedDeclaration",
            "MethodWithMultipleReturnPoints",
            "ReturnOfNull",
            "NestedAssignment",
            "DynamicRegexReplaceableByCompiledPattern",
            "BreakStatement"})

    // avoids hardcoding the tag
    private static final String TAG = Thread.currentThread().getStackTrace()[1].getClassName();

    public Helpers() {
        // dummy constructor
    }

    public static String grabString(Context context, int resID) {
        try {
            return context.getResources().getString(resID);
        } catch (NullPointerException e) {
            Log.e("GRAB_STRING", "" + e);
            return "";
        }
    }

    public static String convertStreamToString(InputStream is) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }

        return sb.toString();
    }

    public static String getStringFromFile(String filePath) throws Exception {
        File fl = new File(filePath);
        FileInputStream fin = new FileInputStream(fl);
        String ret = convertStreamToString(fin);
        fin.close();

        return ret;
    }

    public static Boolean hasBuildPropValue(String buildProp) throws Exception {
        Boolean has = false;
        String buildprop = "";
        buildprop = getStringFromFile(BUILD_PROP);
        if (buildprop.matches(buildProp + "=.+$"))
            has = true;
        return has;
    }

    /**
     * Checks device for SuperUser permission
     *
     * @return If SU was granted or denied
     */
    @SuppressWarnings("MethodWithMultipleReturnPoints")
    public static boolean checkSu() {
        if (!new File("/system/bin/su").exists()
                && !new File("/system/xbin/su").exists()) {
            Log.e(TAG, "su binary does not exist!!!");
            return false; // tell caller to bail...
        }
        try {
            if (runSuCommand("ls /data/app-private").success()) {
                Log.i(TAG, " SU exists and we have permission");
                return true;
            } else {
                Log.i(TAG, " SU exists but we don't have permission");
                return false;
            }
        } catch (NullPointerException e) {
            Log.e(TAG, "NullPointer throw while looking for su binary", e);
            return false;
        }
    }

    /**
     * Checks to see if Busybox is installed in "/system/"
     *
     * @return If busybox exists
     */
    public static boolean checkBusybox() {
        if (!new File("/system/bin/busybox").exists()
                && !new File("/system/xbin/busybox").exists()) {
            Log.e(TAG, "Busybox not in xbin or bin!");
            return false;
        }
        try {
            if (!runSuCommand("busybox mount").success()) {
                Log.e(TAG, "Busybox is there but it is borked! ");
                return false;
            }
        } catch (NullPointerException e) {
            Log.e(TAG, "NullpointerException thrown while testing busybox", e);
            return false;
        }
        return true;
    }

    public static String[] getMounts(CharSequence path) {
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader("/proc/mounts"), 256);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (line.contains(path)) {
                    return line.split(" ");
                }
            }
        } catch (FileNotFoundException ignored) {
            Log.d(TAG, "/proc/mounts does not exist");
        } catch (IOException ignored) {
            Log.d(TAG, "Error reading /proc/mounts");
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ignored) {
                    // ignored
                }
            }
        }
        return null;
    }

    public static boolean getMount(String mount) {
        String[] mounts = getMounts("/system");
        if (mounts != null && mounts.length >= 3) {
            String device = mounts[0];
            String path = mounts[1];
            String point = mounts[2];
            String preferredMountCmd = "mount -o " + mount + ",remount -t " + point + ' ' + device + ' ' + path;
            if (runSuCommand(preferredMountCmd).success()) {
                return true;
            }
        }
        String fallbackMountCmd = "busybox mount -o remount," + mount + " /system";
        return runSuCommand(fallbackMountCmd).success();
    }

    public static String readOneLine(String fname) {
        BufferedReader br = null;
        String line = null;
        try {
            br = new BufferedReader(new FileReader(fname), 1024);
            line = br.readLine();
        } catch (FileNotFoundException ignored) {
            Log.d(TAG, "File was not found! trying via shell...");
            return readFileViaShell(fname, true);
        } catch (IOException e) {
            Log.d(TAG, "IOException while reading system file", e);
            return readFileViaShell(fname, true);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ignored) {
                    // failed to close reader
                }
            }
        }
        return line;
    }

    public static String readFileViaShell(String filePath, boolean useSu) {
        String command = "cat " + filePath;
        return useSu ? runSuCommand(command).getStdout()
                : runShellCommand(command).getStdout();
    }

    public static boolean writeOneLine(String filename, String value) {
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(filename);
            fileWriter.write(value);
        } catch (IOException e) {
            String Error = "Error writing { " + value + " } to file: " + filename;
            Log.e(TAG, Error, e);
            return false;
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException ignored) {
                    // failed to close writer
                }
            }
        }
        return true;
    }

    public static String[] getAvailableIOSchedulers() {
        String[] schedulers = null;
        String[] aux = readStringArray("/sys/block/mmcblk0/queue/scheduler");
        if (aux != null) {
            schedulers = new String[aux.length];
            for (int i = 0; i < aux.length; i++) {
                schedulers[i] = aux[i].charAt(0) == '['
                        ? aux[i].substring(1, aux[i].length() - 1)
                        : aux[i];
            }
        }
        return schedulers;
    }

    private static String[] readStringArray(String fname) {
        String line = readOneLine(fname);
        if (line != null) {
            return line.split(" ");
        }
        return null;
    }

    public static String getIOScheduler() {
        String scheduler = null;
        String[] schedulers = readStringArray("/sys/block/mmcblk0/queue/scheduler");
        if (schedulers != null) {
            for (String s : schedulers) {
                if (s.charAt(0) == '[') {
                    scheduler = s.substring(1, s.length() - 1);
                    break;
                }
            }
        }
        return scheduler;
    }

    /**
     * Long toast message
     *
     * @param context Application Context
     * @param msg     Message to send
     */
    public static void msgLong(Context context, String msg) {
        if (context != null && msg != null) {
            Toast.makeText(context, msg.trim(), Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Short toast message
     *
     * @param context Application Context
     * @param msg     Message to send
     */
    public static void msgShort(Context context, String msg) {
        if (context != null && msg != null) {
            Toast.makeText(context, msg.trim(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * Long toast message
     *
     * @param context Application Context
     * @param msg     Message to send
     */
    public static void sendMsg(Context context, String msg) {
        if (context != null && msg != null) {
            msgLong(context, msg);
        }
    }

    /**
     * Return a timestamp
     *
     * @param context Application Context
     */
    @SuppressWarnings("UnnecessaryFullyQualifiedName")
    public static String getTimestamp(Context context) {
        String timestamp = "unknown";
        Date now = new Date();
        java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context);
        java.text.DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(context);
        timestamp = dateFormat.format(now) + ' ' + timeFormat.format(now);
        return timestamp;
    }

    public static boolean isPackageInstalled(String packageName, PackageManager pm) {
        try {
            String mVersion = pm.getPackageInfo(packageName, 0).versionName;
            if (mVersion == null) {
                return false;
            }
        } catch (PackageManager.NameNotFoundException notFound) {
            Log.e(TAG, "Package could not be found!", notFound);
            return false;
        }
        return true;
    }

    public static void restartSystemUI() {
        startSuCommand("pkill -TERM -f com.android.systemui");
    }

    public static void setSystemProp(String prop, String val) {
        startSuCommand("setprop " + prop + " " + val);
    }

    public static String getSystemProp(Context context, String prop, String def) {
        String result = null;
        try {
            result = SystemPropertiesReflection.get(context, prop);
        } catch (IllegalArgumentException iae) {
            Log.e(TAG, "Failed to get prop: " + prop);
        }
        return result == null ? def : result;
    }

    // If the value is empty or null, fallback to the second property if there's one
    public static String getPropWithFallback(Context context, String[] props, String def) {
        String value = "";
        for (int i = 0; i < props.length; i++) {
            value = Helpers.getSystemProp(context, props[i], def);
            if (!value.equals(""))
                return value;
        }
        return "";
    }

    public static String toMHz(String mhzString) {
        int val = 0;
        try {
            val = Integer.valueOf(mhzString);
        } catch (NumberFormatException e) {
            Log.e("ToMHZ", e.getMessage());
        }
        return val / 1000 + " MHz";
    }

    public static int getNumOfCpus() {
        int numOfCpu = 1;
        String numOfCpus = Helpers.readOneLine("/sys/devices/system/cpu/present");
        String[] cpuCount = numOfCpus.split("-");
        if (cpuCount.length > 1) {
            try {
                int cpuStart = Integer.parseInt(cpuCount[0]);
                int cpuEnd = Integer.parseInt(cpuCount[1]);

                numOfCpu = cpuEnd - cpuStart + 1;

                if (numOfCpu < 0)
                    numOfCpu = 1;
            } catch (NumberFormatException ex) {
                numOfCpu = 1;
            }
        }
        return numOfCpu;
    }

    public static ArrayList<String> getTcpAlgorithms() {
        if (new File("/proc/sys/net/ipv4/tcp_available_congestion_control").exists()) {
            try {
                String result = String.valueOf(runShellCommand("cat /proc/sys/net/ipv4/tcp_available_congestion_control").getStdout());
                Log.e("TCP", result);
                String[] algorithms = result.split("\\s");
                ArrayList<String> holder = new ArrayList<String>();
                Collections.addAll(holder, algorithms);
                return holder;
            } catch (Exception e) {
                Log.e("getTcpAlgorithms", e.getMessage());
                return new ArrayList<String>();
            }

        } else {
            return new ArrayList<String>();
        }
    }

    public static String getCurrentTcpAlgorithm() {
        if (new File("/proc/sys/net/ipv4/tcp_congestion_control").exists()) {
            try {
                return String.valueOf(runShellCommand("cat /proc/sys/net/ipv4/tcp_congestion_control").getStdout());
            } catch (Exception e) {
                Log.e("getCurrentTcpAlgorithm", e.getMessage());
                return "NaN";
            }
        } else return "NaN";
    }

    public static void setPmrProp(String prop, Boolean isOn) {
        if (isOn)
            runSuCommand(Shell.ECHO + "\"" + prop + "=true" + "\" >> " + Shell.BUILD_PROP);
        else
            runSuCommand(Shell.ECHO + "\"" + prop + "=false" + "\" >> " + Shell.BUILD_PROP);
    }

    public static String getProp(String prop) {
        return CMDProcessor.runSuCommand("getprop " + prop).getStdout();
    }

    public static void setpropBoolean(String prop, Boolean isOn) {
        if (isOn)
            runSuCommand("setprop " + prop + " true");
        else
            runSuCommand("setprop " + prop + " false");
    }

    public static void applyBuildPropTweak(String buildProp, String propValue) {
        final String prop = buildProp;
        final String value = propValue;
        new Thread(new Runnable() {

            @Override
            public void run() {
                CMDProcessor.runSuCommand(Shell.MOUNT_SYSTEM_RW);
                CMDProcessor.runSuCommand(Shell.SED + prop + "/d\" " + Shell.BUILD_PROP);
                CMDProcessor.runSuCommand(Shell.ECHO + "\"" + prop + "=" + value + "\" >> " + Shell.BUILD_PROP);
                CMDProcessor.runSuCommand("setprop " + prop + " " + value);
                CMDProcessor.runSuCommand(Shell.MOUNT_SYSTEM_RO);
            }
        }).start();

    }

    /**
     * This method takes a square bitmap and clips it into a circle
     *
     * @param bitmap : the image to clip
     * @return the clipped bitmap
     */
    public static Bitmap getCroppedBitmap(Bitmap bitmap) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        // canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,
                bitmap.getWidth() / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        //Bitmap _bmp = Bitmap.createScaledBitmap(output, 60, 60, false);
        //return _bmp;
        return output;
    }

    /**
     * This method simply allows to open an url with a shorter syntax
     */
    public static void openUrl(ActionBarActivity activity, String url) {
        activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    }

    public static int convertSoundControlValue(int seekBarValue) {
        if (seekBarValue < 0) {
            return seekBarValue + 256;
        } else {
            return seekBarValue;
        }
    }

    public static class CMDProcessorWrapper {
        public static void runSuCommand(final String command) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    CMDProcessor.runSuCommand(command);
                }
            }).start();
        }

        public static void runShellCommand(final String command) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    CMDProcessor.runShellCommand(command);
                }
            }).start();
        }
    }

    public static int getSoundCountrolBitRepresentation(int leftGain, int rightGain) {
        return 0xFF & (0xFFFFFFFF ^ (leftGain & 0xFF) + (rightGain & 0xFF));
    }

    public static Boolean doesFileExist(String path) {
        return new File(path).exists();
    }

    public static void applySysctlValue(String key, String value) {
        Helpers.CMDProcessorWrapper.runSuCommand("busybox mount -o remount,rw /system\n" +
                        "busybox sysctl -w " + key + "=" + value + "\n" +
                        "busybox echo \'" + key + " = " + value + "\' > /system/etc/sysctl.conf\n" +
                        "busybox mount -o remount,ro /system"
        );
    }
} public interface ColorControlInterface {
    public static final String GAMMA_KCAL = "/sys/devices/platform/kcal_ctrl.0/kcal";
    public static final String GAMMA_OK = "/sys/devices/platform/kcal_ctrl.0/kcal_ctrl";
} public interface CPUInterface {
    public static final String CURRENT_CPU = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq";
    public static final String CURRENT_CPU_CPUINFO = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq";
    public static final String MAX_FREQ = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq";
    public static final String MAX_FREQ_ALL_CORES = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq_all_cpus";
    public static final String SNAKE_CHARMER_MAX_FREQ = "/sys/kernel/msm_cpufreq_limit/cpufreq_limit";
    public static final String SNAKE_CHARMER_VERSION = "/sys/kernel/msm_cpufreq_limit/msm_cpufreq_limit_version";
    public static final String TEGRA_MAX_FREQ = "/sys/module/cpu_tegra/parameters/cpu_user_cap";
    public static final String MIN_FREQ = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq";
    public static final String MIN_FREQ_ALL_CORES = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq_all_cpus";
    public static final String STEPS = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies";
    public static final String ONLINE_CPUS = "/sys/devices/system/cpu/online";
    public static final String OFFLINE_CPUS = "/sys/devices/system/cpu/offline";
    public static final String CPU0_ONLINE = "/sys/devices/system/cpu/cpu0/online";
    public static final String CPU1_ONLINE = "/sys/devices/system/cpu/cpu1/online";
    public static final String CPU2_ONLINE = "/sys/devices/system/cpu/cpu2/online";
    public static final String CPU3_ONLINE = "/sys/devices/system/cpu/cpu3/online";
    public static final String GOVERNORS_LIST = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors";
    public static final String GOVERNORS_LIST2 = "/sys/devices/system/cpu/cpu1/cpufreq/scaling_available_governors";
    public static final String GOVERNORS_LIST3 = "/sys/devices/system/cpu/cpu2/cpufreq/scaling_available_governors";
    public static final String GOVERNORS_LIST4 = "/sys/devices/system/cpu/cpu3/cpufreq/scaling_available_governors";
    public static final String FIRST_PART_CPU = "/sys/devices/system/cpu/cpu";
    public static final String SECOND_PART_GOV = "/cpufreq/scaling_governor";
    public static final String SECOND_PART_ONLINE = "/online";
    public static final String GOVERNOR = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor";
    public static final String GOVERNOR2 = "/sys/devices/system/cpu/cpu1/cpufreq/scaling_governor";
    public static final String GOVERNOR3 = "/sys/devices/system/cpu/cpu2/cpufreq/scaling_governor";
    public static final String GOVERNOR4 = "/sys/devices/system/cpu/cpu3/cpufreq/scaling_governor";
    public static final String GOVERNOR_ALL_CORES = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor_all_cpus";
    public static final String IO_SCHEDULER = "/sys/block/mmcblk0/queue/scheduler";
    public static final String NUM_OF_CPUS = "/sys/devices/system/cpu/present";
    public static final String AVAILABLE_TCP_ALGORITHMS = "/proc/sys/net/ipv4/tcp_available_congestion_control";
    public static final String CURR_TCP_ALGORITHM = "/proc/sys/net/ipv4/tcp_congestion_control";
    public static final String SYSCTL_TCP_ALGORITHM = "sysctl -w net.ipv4.tcp_congestion_control=";
    public static final String MSM_THERMAL = "/sys/module/msm_thermal/parameters/enabled";
    public static final String KRAIT_BOOST = "/sys/module/clock_krait_8974/parameters/boost";
    public static final String PVS_BINNING = "/sys/module/clock_krait_8974/parameters/table_name";
    public static final String GOV_CUSTOMIZATION = "/sys/devices/system/cpu/cpufreq";
} public interface GPUInterface {
    public static String availableFreqs = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpu_available_frequencies";
    public static String availableGovernors = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/available_governors";
    public static String currGovernor = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/governor";
    public static String maxFreq = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/max_gpuclk";
    public static String minFreq = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/min_freq";
    public static String currFreq = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/cur_freq";
} public interface IOTweaksInterface {
    public static final String DYNAMIC_FSYNC_VERSION = "/sys/kernel/dyn_fsync/Dyn_fsync_version";
    public static final String DYNAMIC_FSYNC_TOGGLE = "/sys/kernel/dyn_fsync/Dyn_fsync_active";
    public static final String IO_SCHEDULER = "/sys/block/mmcblk0/queue/scheduler";
    public static final String IO_SCHEDULER_SD = "/sys/block/mmcblk1/queue/scheduler";
    public static final String EMMC_ENTROPY_CONTRIB = "/sys/block/mmcblk0/queue/add_random";
    public static final String SD_ENTROPY_CONTRIB = "/sys/block/mmcblk1/queue/add_random";
    public static final String EMMC_READAHEAD = "/sys/block/mmcblk0/queue/read_ahead_kb";
    public static final String SD_READAHEAD = "/sys/block/mmcblk1/queue/read_ahead_kb";
} public interface MemoryManagementInterface {
    public static final String KSM_TOGGLE = "/sys/kernel/mm/ksm/run";
    public static final String KSM_PAGES_TO_SCAN = "/sys/kernel/mm/ksm/pages_to_scan";
    public static final String KSM_SLEEP_TIMER = "/sys/kernel/mm/ksm/sleep_millisecs";
    public static final String VFS_CACHE_PRESSURE = "vm.vfs_cache_pressure";
    public static final String SWAPPINESS = "vm.swappiness";
    public static final String DIRTY_RATIO = "vm.dirty_ratio";
    public static final String DIRTY_BG_RATIO = "vm.dirty_background_ratio";
    public static final String DIRTY_WRITEBACK_CENTISECS = "vm.dirty_writeback_centisecs";
    public static final String DIRTY_EXPIRE_CENTISECS = "vm.dirty_expire_centisecs";
} public interface MiscInterface {
    public static final String VIBRATOR_SYSFS = "/sys/devices/virtual/timed_output/vibrator/vtg_level";
    public static final String FORCE_FAST_CHARGE = "/sys/kernel/fast_charge/force_fast_charge";
    public static final String FAST_CHARGE_LEVEL = "/sys/kernel/fast_charge/fast_charge_level";
    public static final String AVAILABLE_FAST_CHARGE_LEVELS = "/sys/kernel/fast_charge/available_charge_levels";
    public static final String FAST_CHARGE_VERSION = "/sys/kernel/fast_charge/version";
} public interface PowerManagementInterface {
    public static final String SCHED_MC_POWER_SAVINGS = "/sys/devices/system/cpu/sched_mc_power_savings";
    public static final String INTELLI_PLUG_TOGGLE = "/sys/module/intelli_plug/parameters/intelli_plug_active";
    public static final String INTELLI_PLUG_ECO_MODE = "/sys/module/intelli_plug/parameters/eco_mode_active";
    public static final String INTELLI_PLUG_ECO_CORES = "/sys/module/intelli_plug/parameters/eco_cores_enabled";
    public static final String ALUCARD_HOTPLUG_TOGGLE = "/sys/kernel/alucard_hotplug/hotplug_enable";
    public static final String ALUCARD_HOTPLUG_CORES = "/sys/kernel/alucard_hotplug/maxcoreslimit";
    public static final String MSM_MPDECISION_TOGGLE = "/sys/kernel/msm_mpdecision/conf/enabled";
    public static final String POWER_SUSPEND_TOGGLE = "/sys/kernel/power_suspend/power_suspend_mode";
} public interface VoltageInterface {
    public static final String UV_MV_TABLE = "/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table";
} public interface SoundControlInterface {
    public static final String FAUX_SC_LOCKED = "/sys/kernel/sound_control_3/gpl_sound_control_locked";
    public static final String FAUX_SC_VERSION = "/sys/kernel/sound_control_3/gpl_sound_control_version";
    public static final String FAUX_SC_HEADPHONE = "/sys/kernel/sound_control_3/gpl_headphone_gain";
    public static final String FAUX_SC_HEADPHONE_POWERAMP = "/sys/kernel/sound_control_3/gpl_headphone_pa_gain";
    public static final String FAUX_SC_MIC = "/sys/kernel/sound_control_3/gpl_mic_gain";
    public static final String FAUX_SC_CAM_MIC = "/sys/kernel/sound_control_3/gpl_cam_mic_gain";
    public static final String FAUX_SC_SPEAKER = "/sys/kernel/sound_control_3/gpl_speaker_gain";
} public interface TouchScreenInterface {
    public static final String PEN_MODE = "/sys/devices/virtual/input/clearpad/pen";
    public static final String GLOVE_MODE = "/sys/devices/virtual/input/clearpad/glove";
    public static final String CLEARPAD = "/system/usr/idc/clearpad.idc";
    public static final String CLEARPAD_PEN = "/system/usr/idc/clearpad_pen.idc";
    public static final String DT2WAKE = "/sys/devices/virtual/input/clearpad/wakeup_gesture";
}
import com.androguide.honamicontrol.kernel.iotweaks.IOTweaksInterface;
import com.androguide.honamicontrol.kernel.memory.MemoryManagementInterface;
import com.androguide.honamicontrol.kernel.misc.MiscInterface;
import com.androguide.honamicontrol.kernel.powermanagement.PowerManagementInterface;
import com.androguide.honamicontrol.kernel.voltagecontrol.VoltageInterface;
import com.androguide.honamicontrol.soundcontrol.SoundControlInterface;
import com.androguide.honamicontrol.touchscreen.TouchScreenInterface;
import android.content.Context;
import android.content.SharedPreferences;
import com.androguide.honamicontrol.helpers.CMDProcessor.CMDProcessor;
import com.androguide.honamicontrol.helpers.CPUHelper;
import com.androguide.honamicontrol.helpers.Helpers;
import com.androguide.honamicontrol.kernel.colorcontrol.ColorControlInterface;
import com.androguide.honamicontrol.kernel.cpucontrol.CPUInterface;
import com.androguide.honamicontrol.kernel.gpucontrol.GPUInterface;
/**   Copyright (C) 2013  Louis Teboul (a.k.a Androguide)
 *
 *    admin@pimpmyrom.org  || louisteboul@gmail.com
 *    http://pimpmyrom.org || http://androguide.fr
 *    71 quai Clémenceau, 69300 Caluire-et-Cuire, FRANCE.
 *
 *     This program is free software; you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation; either version 2 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License along
 *      with this program; if not, write to the Free Software Foundation, Inc.,
 *      51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 **/

package com.androguide.honamicontrol.bootservice;



public class BootHelper {
    public static void generateScriptFromPrefs(SharedPreferences prefs, Context context) {
        int CPU_MAX_FREQ = Integer.valueOf(prefs.getString("CPU_MAX_FREQ", "2150400"));
        int CPU_MIN_FREQ = Integer.valueOf(prefs.getString("CPU_MIN_FREQ", "300000"));
        int GPU_MAX_FREQ = Integer.valueOf(prefs.getString("GPU_MAX_FREQ", "450000000"));
        int GPU_MIN_FREQ = Integer.valueOf(prefs.getString("GPU_MIN_FREQ", "200000000"));
        int SCHED_MC_LEVEL = prefs.getInt("SCHED_MC_LEVEL", 0);
        int KSM_PAGES_TO_SCAN = prefs.getInt(MemoryManagementInterface.KSM_PAGES_TO_SCAN.replaceAll("/", "_"), 100);