package com.example.modifier.ui

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

private const val TAG = "Modifier"
suspend fun shellRun(vararg commands: String): Map<String, String> {
    var output = ""
    var error = ""
    Log.i(TAG, "shellRun: \t${commands.joinToString("\n\t\t\t")}")
    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 {
                    it.forEach {
                        output += it + "\n"
                        Log.i(TAG, "shellRunOut: $it")
                    }
                }
            }
            launch {
                p.errorStream.bufferedReader().useLines {
                    it.forEach {
                        error += it + "\n"
                        Log.e(TAG, "shellRunErr: $it")
                    }
                }
            }
        }
        p.waitFor()
    }
    return mapOf("output" to output, "error" to error)
}