package com.example.modifier.utils

import android.util.Log
import com.example.modifier.baseTag
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

const val shellTag = "$baseTag/shell"
suspend fun shellRun(vararg commands: String): Pair<String, String> {
    if (!ROOT_ACCESS) {
        val res = ADB.adbShell(*commands)
        return Pair(res.output, res.error)
    }
    var output = ""
    var error = ""
    Log.i(shellTag, "shellRun: \t${commands.joinToString("\n\t\t\t")}")
    runCatching {
        withContext(Dispatchers.IO) {
            val p = ProcessBuilder("su", "-M").start()
            p.outputStream.bufferedWriter().use { writer ->
                commands.forEach { command ->
                    writer.write(command)
                    writer.newLine()
                    writer.flush()
                }
            }
            coroutineScope {
                launch {
                    p.inputStream.bufferedReader().useLines { line ->
                        line.forEach {
                            output += it + "\n"
                            Log.i(shellTag, "shellRunOut: $it")
                        }
                    }
                }
                launch {
                    p.errorStream.bufferedReader().useLines { line ->
                        line.forEach {
                            error += it + "\n"
                            Log.e(shellTag, "shellRunErr: $it")
                        }
                    }
                }
            }
            p.waitFor()
        }
    }.onFailure {
        error = it.message ?: "Unknown error"
        Log.e(shellTag, "shellRun: $error")
    }
    return Pair(output, error)
}