package com.ifpdos.daemonserver.j;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.text.TextUtils;
import android.util.Log;
import com.ifpdos.daemonserver.App;
import com.ifpdos.mosquitto.Mosqiutto;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.lang.Thread;

/* JADX INFO: compiled from: Tools.java */
/* JADX INFO: loaded from: classes.dex */
public class f {

    /* JADX INFO: renamed from: a, reason: collision with root package name */
    private static final String f1526a;

    /* JADX INFO: renamed from: b, reason: collision with root package name */
    private static final String f1527b;

    /* JADX INFO: renamed from: c, reason: collision with root package name */
    private static Thread f1528c;

    static {
        String str;
        f1526a = Build.VERSION.SDK_INT >= 30 ? "persist.sys.mqtt_broker_init" : "persist.ctm.mqtt_broker_init";
        if (m()) {
            str = "/data/data/" + App.f1492b.getPackageName() + "/files/";
        } else {
            str = "/system/bin/";
        }
        f1527b = str;
    }

    public static void A(Context context) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.ifpdos.team", "com.ifpdos.team.TeamService"));
        context.startService(intent);
    }

    private static boolean B(File file) {
        if (file.exists()) {
            return true;
        }
        try {
            return file.createNewFile();
        } catch (IOException e2) {
            Log.e("Tools", "checkCreateFile", e2);
            return false;
        }
    }

    /* JADX WARN: Multi-variable type inference failed */
    /* JADX WARN: Type inference failed for: r0v0 */
    /* JADX WARN: Type inference failed for: r0v1 */
    /* JADX WARN: Type inference failed for: r0v10 */
    /* JADX WARN: Type inference failed for: r0v11 */
    /* JADX WARN: Type inference failed for: r0v2, types: [java.io.FileOutputStream] */
    /* JADX WARN: Type inference failed for: r0v3, types: [java.io.FileOutputStream] */
    /* JADX WARN: Type inference failed for: r0v4 */
    /* JADX WARN: Type inference failed for: r0v5 */
    /* JADX WARN: Type inference failed for: r0v6 */
    /* JADX WARN: Type inference failed for: r0v7 */
    /* JADX WARN: Type inference failed for: r0v9 */
    public static void C(InputStream inputStream, File file) throws Throwable {
        FileOutputStream fileOutputStream;
        int i;
        ?? r0 = 0;
        r0 = 0;
        try {
            try {
                try {
                    fileOutputStream = new FileOutputStream(file);
                } catch (IOException unused) {
                }
            } catch (IOException e2) {
                e = e2;
            }
        } catch (Throwable th) {
            th = th;
        }
        try {
            try {
                byte[] bArr = new byte[1024];
                while (true) {
                    i = inputStream.read(bArr);
                    if (i == -1) {
                        break;
                    } else {
                        fileOutputStream.write(bArr, 0, i);
                    }
                }
                fileOutputStream.close();
                r0 = i;
            } catch (IOException e3) {
                e = e3;
                r0 = fileOutputStream;
                e.printStackTrace();
                if (r0 != 0) {
                    r0.close();
                    r0 = r0;
                }
                inputStream.close();
            } catch (Throwable th2) {
                th = th2;
                r0 = fileOutputStream;
                if (r0 != 0) {
                    try {
                        r0.close();
                    } catch (IOException unused2) {
                    }
                }
                try {
                    inputStream.close();
                    throw th;
                } catch (IOException unused3) {
                    throw th;
                }
            }
            inputStream.close();
        } catch (IOException unused4) {
        }
    }

    public static void a(String str, File file) throws Throwable {
        FileWriter fileWriter;
        FileWriter fileWriter2 = null;
        try {
            try {
                try {
                    fileWriter = new FileWriter(file, true);
                } catch (IOException e2) {
                    e = e2;
                }
            } catch (Throwable th) {
                th = th;
            }
            try {
                fileWriter.append((CharSequence) str);
                fileWriter.flush();
                fileWriter.close();
            } catch (IOException e3) {
                e = e3;
                fileWriter2 = fileWriter;
                e.printStackTrace();
                if (fileWriter2 == null) {
                } else {
                    fileWriter2.close();
                }
            } catch (Throwable th2) {
                th = th2;
                fileWriter2 = fileWriter;
                if (fileWriter2 != null) {
                    try {
                        fileWriter2.close();
                    } catch (IOException unused) {
                    }
                }
                throw th;
            }
        } catch (IOException unused2) {
        }
    }

    public static void b() {
        SystemProperties.set(f1526a, "false");
    }

    public static boolean c(String str, String str2, boolean z) {
        StringBuilder sb = new StringBuilder();
        sb.append("cp");
        sb.append(z ? " -f " : " ");
        sb.append(str);
        sb.append(" ");
        sb.append(str2);
        return e.a(sb.toString()).f1524a == 0;
    }

    public static void d() {
        new Thread(new Runnable() { // from class: com.ifpdos.daemonserver.j.a
            @Override // java.lang.Runnable
            public final void run() {
                f.n();
            }
        }).start();
    }

    private static String e(Context context) {
        return new File(context.getFilesDir(), "mosquitto.log").getAbsolutePath();
    }

    public static String f(Context context) {
        return (Build.VERSION.SDK_INT < 33 || !B(new File("/mnt/tmp/mosquitto.log"))) ? B(new File("/data/mosquitto.log")) ? "/data/mosquitto.log" : e(context) : "/mnt/tmp/mosquitto.log";
    }

    private static String g() {
        int i;
        String str = e.a("ps -ef | grep mosquitto | busybox awk '{print $1,$2,$3,$8}'").f1525b;
        if (TextUtils.isEmpty(str)) {
            return "";
        }
        try {
        } catch (Exception unused) {
        }
        for (String str2 : str.split("\n")) {
            if (str2.contains("mosquitto") && !str2.contains("grep")) {
                return str2.split(" ")[1];
            }
            return "";
        }
        return "";
    }

    public static boolean h() {
        return SystemProperties.getBoolean("persist.sys.router", false);
    }

    public static boolean i(Context context, String str) {
        if (str == null || "".equals(str)) {
            return false;
        }
        try {
            int applicationEnabledSetting = context.getPackageManager().getApplicationEnabledSetting(str);
            return (applicationEnabledSetting == 2 || applicationEnabledSetting == 3) ? false : true;
        } catch (Exception unused) {
            return false;
        }
    }

    public static boolean j() {
        return "host".equals(SystemProperties.get("ro.CVT_DEF_DUAL_SCREEN_TYPE", "normal"));
    }

    public static boolean k() {
        String str = e.a("ping -c 2 -t 1 192.168.153.1").f1525b;
        return !TextUtils.isEmpty(str) && str.contains("64 bytes from");
    }

    public static boolean l() {
        return "slave".equals(SystemProperties.get("ro.CVT_DEF_DUAL_SCREEN_TYPE", "normal"));
    }

    private static boolean m() {
        return d.c() || Build.VERSION.SDK_INT >= 30 || d.b() || SystemProperties.getInt("persis.sys.broker.workmode", 0) == 1;
    }

    static /* synthetic */ void n() {
        Log.d("Tools", "exportLog");
        String strF = f(App.f1492b);
        try {
            Runtime.getRuntime().exec("cp " + strF + " /sdcard/mosquitto.log").waitFor();
            Log.d("Tools", "exportLog finish");
        } catch (Exception e2) {
            Log.d("Tools", "", e2);
        }
    }

    static /* synthetic */ void o(boolean z) {
        try {
            Log.d("Tools", "mqtt server start");
            if (!m()) {
                v();
                return;
            }
            for (int i = 0; i < 3 && f1528c != null && !f1528c.isInterrupted(); i++) {
                long jElapsedRealtime = SystemClock.elapsedRealtime();
                u();
                long jElapsedRealtime2 = SystemClock.elapsedRealtime() - jElapsedRealtime;
                Log.d("Tools", "jni run " + jElapsedRealtime2);
                if (!z || jElapsedRealtime2 >= 3000) {
                    return;
                }
                Log.d("Tools", "broker init fail, retry");
                Thread.sleep(5000L);
            }
        } catch (Exception e2) {
            Log.e("Tools", "", e2);
        }
    }

    public static void q(String str) {
        Log.d("Tools", str);
        e.a(String.format("echo %s >> /sdcard/.AbnormalLog/network.txt", str.trim().replace(" ", "_")));
    }

    public static void r() {
        x(App.f1492b);
        App.f1492b.sendBroadcast(new Intent("com.ifpdos.monitor.http_lost"));
    }

    public static void s() {
        x(App.f1492b);
        App.f1492b.sendBroadcast(new Intent("com.ifpdos.monitor.mqtt_lost"));
    }

    public static void t() {
        if (d.d()) {
            e.a("mount -o remount,rw -t ext4 /dev/root");
        } else {
            e.a("mount -o rw,remount /system");
        }
    }

    private static void u() {
        Log.d("Tools", "runByJNI");
        if (new File("/sdcard/mosquitto.conf").exists()) {
            Mosqiutto.start("/sdcard/mosquitto.conf");
        } else {
            Mosqiutto.start(f1527b + "mosquitto.conf");
        }
        if (Mosqiutto.isRunning()) {
            Log.d("Tools", "mosqiutto is running, stop");
            Mosqiutto.stop();
        }
        Log.d("Tools", "runByJNI end");
    }

    private static void v() {
        Log.d("Tools", "runByShell");
        e.a("cd " + f1527b + " && chmod 777 mosquitto && chmod 777 mosquitto.conf");
        e.a("cd " + f1527b + " && ./mosquitto -c mosquitto.conf -d");
        Log.d("Tools", "runByShell end");
    }

    public static boolean w(Context context) throws Throwable {
        Log.d("Tools", "setupBroker WORK_DIR " + f1527b);
        File file = new File(f1527b, "mosquitto");
        File file2 = new File(f1527b, "mosquitto.conf");
        if (file.exists() && file2.exists() && SystemProperties.getBoolean(f1526a, false)) {
            com.ifpdos.daemonserver.i.c.a("Tools", "mqtt broker file exist");
            return true;
        }
        try {
            com.ifpdos.daemonserver.i.c.a("Tools", "start setup mqtt broker");
            if (m()) {
                File file3 = new File(context.getFilesDir(), "mosquitto.conf");
                C(context.getAssets().open("mosquitto_inner.conf"), file3);
                a("\ncertfile " + f1527b + "server.crt\nkeyfile " + f1527b + "server.key\ncafile " + f1527b + "ca.crt\n", file3);
            } else {
                C(context.getAssets().open("mosquitto"), new File(context.getFilesDir(), "mosquitto"));
                C(context.getAssets().open("mosquitto.conf"), new File(context.getFilesDir(), "mosquitto.conf"));
            }
            C(context.getAssets().open("ca.crt"), new File(context.getFilesDir(), "ca.crt"));
            C(context.getAssets().open("server.crt"), new File(context.getFilesDir(), "server.crt"));
            C(context.getAssets().open("server.key"), new File(context.getFilesDir(), "server.key"));
            if (!m()) {
                t();
                boolean zC = c(new File(context.getFilesDir(), "server.crt").getAbsolutePath(), f1527b, false) & c(new File(context.getFilesDir(), "ca.crt").getAbsolutePath(), f1527b, false) & c(new File(context.getFilesDir(), "mosquitto").getAbsolutePath(), f1527b, false) & c(new File(context.getFilesDir(), "mosquitto.conf").getAbsolutePath(), f1527b, false) & c(new File(context.getFilesDir(), "server.key").getAbsolutePath(), f1527b, false);
                e.a("sync");
                SystemProperties.set(f1526a, "true");
                return zC;
            }
            File file4 = new File(context.getFilesDir(), "mosquitto.conf");
            String strF = f(context);
            File file5 = new File(strF);
            Log.d("Tools", "brokerLogPath:" + strF);
            if (file5.exists() && file5.length() > 104857600) {
                Log.d("Tools", "delete log file:" + file5.getAbsolutePath());
                file5.delete();
            }
            a(String.format("log_dest file %s\n", strF), file4);
            if (SystemProperties.getInt("persist.sys.log.on", 0) == 1 || SystemProperties.getBoolean("persist.sys.log.enable", false)) {
                a("log_type debug\n", file4);
                if (d.e()) {
                    e.a("mkdir -p /data/misc/last_logd");
                    e.a(String.format("mv %s /data/misc/last_logd/mosquitto.log", strF));
                    e.a(String.format("touch %s", strF));
                }
            }
            SystemProperties.set(f1526a, "true");
            return true;
        } catch (Exception e2) {
            Log.e("Tools", "", e2);
            return false;
        }
    }

    public static void x(Context context) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.ifpdos.monitor", "com.ifpdos.monitor.MainService"));
        context.startService(intent);
    }

    public static void y(boolean z) {
        z(z, false);
    }

    public static void z(boolean z, final boolean z2) {
        Log.d("Tools", "startMQTTServer force=" + z + " retry=" + z2);
        if (!m()) {
            String strG = g();
            if (!TextUtils.isEmpty(strG)) {
                if (!z) {
                    Log.d("Tools", "MQTT Server is running, return");
                    return;
                }
                Log.d("Tools", "MQTT Server is running, kill");
                e.a("kill " + strG);
            }
        } else if (Mosqiutto.isRunning()) {
            if (z) {
                Log.d("Tools", "mosqiutto is running, force stop");
                Mosqiutto.stop();
            } else {
                Log.d("Tools", "mosqiutto is running, return");
            }
        }
        Thread thread = f1528c;
        if (thread != null) {
            thread.interrupt();
        }
        Thread thread2 = new Thread(new Runnable() { // from class: com.ifpdos.daemonserver.j.b
            @Override // java.lang.Runnable
            public final void run() {
                f.o(z2);
            }
        });
        f1528c = thread2;
        thread2.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { // from class: com.ifpdos.daemonserver.j.c
            @Override // java.lang.Thread.UncaughtExceptionHandler
            public final void uncaughtException(Thread thread3, Throwable th) {
                Log.d("Tools", "MqttThread crash", th);
            }
        });
        f1528c.start();
    }
}
