#!/bin/sh
# Kept in manager arguments, never read back from a mutable payload file.
set -eu
fail() { printf 'cleanup refused: %s\n' "$*" >&2; exit 1; }
[ "$#" -eq 3 ] || fail 'expected HOME WORKSPACE NONCE'
home=$1
workspace=$2
nonce=$3
case "$nonce" in *[!0-9a-f]*|'') fail 'invalid nonce' ;; esac
[ "${#nonce}" -eq 16 ] || fail 'invalid nonce length'
case "$home" in /*) ;; *) fail 'home must be absolute' ;; esac
case "$home" in *[!a-zA-Z0-9/_.-]*|/|*/) fail 'unsafe home' ;; esac
[ "$(id -u)" = 1000 ] && [ "$(id -g)" = 1000 ] || fail 'requires UID/GID1000'
[ ! -L "$home" ] || fail 'home symlink'
[ "$(CDPATH='' cd -- "$home" && pwd -P)" = "$home" ] || fail 'noncanonical home'
home_stat=$(stat -c '%u:%g:%a' -- "$home")
case "$home_stat" in 1000:1000:700|1000:1000:750|1000:1000:755) ;;
    *) fail 'ambiguous home ownership or permissions' ;;
esac
[ "$workspace" = "$home/.pi-c-s0-$nonce" ] || fail 'workspace mismatch'
[ ! -L "$workspace" ] || fail 'workspace symlink'
if [ ! -e "$workspace" ]; then
    printf 'cleanup: absent\n'
    exit 0
fi
[ -d "$workspace" ] || fail 'workspace is not a directory'
[ "$(stat -c '%u:%g:%a' -- "$workspace")" = 1000:1000:700 ] || fail 'workspace owner/mode'
[ "$(CDPATH='' cd -- "$workspace" && pwd -P)" = "$workspace" ] || fail 'noncanonical workspace'
marker="$workspace/.pi-c-owner"
[ ! -L "$marker" ] && [ -f "$marker" ] || fail 'missing or symlink marker'
[ "$(stat -c '%u:%g:%a' -- "$marker")" = 1000:1000:600 ] || fail 'marker owner/mode'
[ "$(wc -c < "$marker")" -eq 17 ] || fail 'marker size'
[ "$(cat "$marker")" = "$nonce" ] || fail 'marker mismatch'
rm -rf -- "$workspace"
[ ! -e "$workspace" ] && [ ! -L "$workspace" ] || fail 'workspace remains'
printf 'cleanup: removed\n'
