#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
set -euo pipefail
(( EUID == 0 )) || exit 1
project=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)
python3 - "$project/build" <<'PY'
import re
import shutil
import sys
from pathlib import Path

work = Path(sys.argv[1])
if work.is_symlink():
    raise ValueError("Build directory must not be a symlink")
targets = [work / name for name in ("controller", "chroots", "tmp")]
inputs = work / "input"
for target in [*targets, inputs]:
    if target.is_symlink():
        raise ValueError("Environment directory must not be a symlink: " + str(target))
for line in Path("/proc/self/mountinfo").read_text().splitlines():
    value = re.sub(r"\\([0-7]{3})", lambda match: chr(int(match[1], 8)), line.split()[4])
    mountpoint = Path(value)
    if any(mountpoint == target or mountpoint.is_relative_to(target) for target in [*targets, inputs]):
        raise ValueError("Environment contains an active mount: " + str(mountpoint))
if inputs.exists():
    targets.extend(path for path in inputs.iterdir() if path.name != "modules")
for target in targets:
    if target.is_symlink() or target.is_file():
        target.unlink()
    elif target.exists():
        shutil.rmtree(target)
for relative in ("controller-bootstrap.complete", "records/build-root.sha256"):
    (work / relative).unlink(missing_ok=True)
print("Build environment removed. Run tools/plasma-next setup to recreate it.")
PY
