#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2026 Adam Mercer
#
# smoketest: check, from inside the guest, the machine behaviours kelder
# relies on. `kelder self smoketest` runs it in a throwaway machine; by hand:
#
#   VM=kelder-test kelder self setup
#   VM=kelder-test kelder     then, in that session: smoketest [DIR]
#
# DIR is an attached host directory (default: the current directory).
# Each line is PASS or FAIL. Exits non-zero if anything FAILs.
set -uo pipefail

dir=${1:-$PWD}
image=docker.io/library/python:3-slim
fails=0
pass()    { printf 'PASS     %s\n' "$1"; }
fail()    { printf 'FAIL     %s\n' "$1"; fails=$((fails + 1)); }

# --- users -------------------------------------------------------------------
uid=$(id -u)
# Sessions run as a user with the host user's uid, who may sudo.
owner=$(stat -c %u "$dir")
if [[ $uid == "$owner" ]]; then pass "session runs as uid $uid, the owner of $dir"
else fail "session runs as uid $uid, $dir belongs to uid $owner"; fi

if sudo -n true 2>/dev/null; then pass "sudo works without a password"
else fail "sudo needs a password or is not allowed"; fi

# --- attached directory ownership --------------------------------------------
if ! tmp=$(mktemp -p "$dir" .smoketest.XXXXXX); then
  fail "cannot create a file in $dir"
else
  owner=$(stat -c %u "$dir")
  got=$(stat -c %u "$tmp")
  if [[ $got == "$owner" ]]; then
    rm -f "$tmp"
    pass "files the session creates in $dir belong to uid $owner, the directory's owner"
  else
    fail "files the session creates in $dir belong to uid $got, the directory belongs to uid $owner (kept $tmp)"
  fi
fi

# --- containers --------------------------------------------------------------
if ! podman pull -q "$image" >/dev/null; then
  fail "cannot pull $image; container checks skipped"
else
  # A second send on a connected UDP socket in a container: glibc's resolver
  # does this, and a machine without a real network card has failed it.
  udp='import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("1.1.1.1", 53))
try:
    s.send(b"x"); s.send(b"x"); print("ok")
except OSError as e:
    print(e.errno)'
  # Only what the check prints decides: podman's own warnings go to stderr.
  r=$(podman run --rm "$image" python3 -c "$udp")
  if [[ $r == ok ]]; then pass "connected UDP in containers works"
  else fail "container UDP check gave: $r"; fi

  if podman run --rm "$image" getent ahosts deb.debian.org >/dev/null; then
    pass "container DNS resolves"
  else
    fail "container DNS fails"
  fi
fi

# --- nested VMs --------------------------------------------------------------
if testvm run -- true; then pass "testvm boots a nested VM"
else fail "testvm cannot boot a nested VM"; fi

echo
if ((fails)); then echo "$fails check(s) failed"; exit 1; fi
echo "all checks passed"
