/* Title: Pure/System/linux.scala
Author: Makarius
Specific support for Linux, notably Ubuntu/Debian.
*/
package isabelle
import scala.util.matching.Regex
object Linux
{
/* check system */
def check_system(): Unit =
if (!Platform.is_linux) error("Not a Linux system")
def check_system_root(): Unit =
{
check_system()
if (Isabelle_System.bash("id -u").check.out != "0") error("Not running as superuser (root)")
}
/* release */
object Release
{
private val ID = """^Distributor ID:\s*(\S.*)$""".r
private val RELEASE = """^Release:\s*(\S.*)$""".r
private val DESCRIPTION = """^Description:\s*(\S.*)$""".r
def apply(): Release =
{
val lines = Isabelle_System.bash("lsb_release -a").check.out_lines
def find(R: Regex): String = lines.collectFirst({ case R(a) => a }).getOrElse("Unknown")
new Release(find(ID), find(RELEASE), find(DESCRIPTION))
}
}
final class Release private(val id: String, val release: String, val description: String)
{
override def toString: String = description
def is_ubuntu: Boolean = id == "Ubuntu"
}
/* packages */
def reboot_required(): Boolean =
Path.explode("/var/run/reboot-required").is_file
def check_reboot_required(): Unit =
if (reboot_required()) error("Reboot required")
def package_update(progress: Progress = No_Progress): Unit =
progress.bash(
"""apt-get update -y && apt-get upgrade -y && apt autoremove -y""",
echo = true).check
def package_install(packages: List[String], progress: Progress = No_Progress): Unit =
progress.bash("apt-get install -y -- " + Bash.strings(packages), echo = true).check
/* users */
def user_exists(name: String): Boolean =
Isabelle_System.bash("id " + Bash.string(name)).ok
def user_entry(name: String, field: Int): String =
{
val result = Isabelle_System.bash("getent passwd " + Bash.string(name)).check
val fields = space_explode(':', result.out)
if (1 <= field && field <= fields.length) fields(field - 1)
else error("No passwd field " + field + " for user " + quote(name))
}
def user_description(name: String): String = user_entry(name, 5).takeWhile(_ != ',')
def user_home(name: String): String = user_entry(name, 6)
def user_add(name: String, description: String = "", ssh_setup: Boolean = false)
{
require(!description.contains(','))
if (user_exists(name)) error("User already exists: " + quote(name))
Isabelle_System.bash(
"adduser --quiet --disabled-password --gecos " + Bash.string(description) +
" " + Bash.string(name)).check
if (ssh_setup) {
val id_rsa = user_home(name) + "/.ssh/id_rsa"
Isabelle_System.bash("""
if [ ! -f """ + Bash.string(id_rsa) + """ ]
then
yes '\n' | sudo -i -u """ + Bash.string(name) +
""" ssh-keygen -q -f """ + Bash.string(id_rsa) + """
fi
""").check
}
}
}