#!/bin/bash
# Copyright 2026 ANNE Media - https://anne.media
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# exit_chroot.sh – unmount virtual filesystems of the Slackware build chroot
# Run as:  sudo /home/annestar/amos-current/exit_chroot.sh [--lazy]

set -u
BUILD_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
CHROOT_DIR="$(cd -- "$BUILD_DIR/../.." && pwd -P)"
LAZY=""

case "${1:-}" in
    ""|--lazy|-l) [ "${1:-}" = "--lazy" -o "${1:-}" = "-l" ] && LAZY="-l" ;;
    *) echo "Usage: $0 [--lazy]"; exit 1 ;;
esac

[ "$(id -u)" -eq 0 ] || { echo "Must be run as root: sudo $0" >&2; exit 1; }
[ -d "$CHROOT_DIR" ] || { echo "ERROR: chroot directory $CHROOT_DIR not found"; exit 1; }

[ -n "$LAZY" ] && echo "Using lazy unmount (umount -l)."

echo "Unmounting virtual filesystems from $CHROOT_DIR ..."

echo ">>> Mounts currently under $CHROOT_DIR:"
if mount | grep -q " $CHROOT_DIR"; then
    mount | grep " $CHROOT_DIR"
else
    echo "    (none)"
fi

fail=0
for mnt in dev/pts dev sys proc; do
    t="$CHROOT_DIR/$mnt"
    if mountpoint -q "$t"; then
        echo "  Unmounting $t"
        if ! umount $LAZY "$t"; then
            echo "  WARNING: $t busy, retrying recursive+lazy"
            umount -R -l "$t" 2>/dev/null || { echo "  FAILED: $t still mounted"; fail=1; }
        fi
    else
        echo "  $t not mounted, skipping."
    fi
done

# Safety: never chown through a bind mount.
if mount | grep -q " $CHROOT_DIR/"; then
    echo "ERROR: mounts still present under $CHROOT_DIR; skipping chown to avoid"
    echo "       touching host /dev, /proc, or /sys through bind mounts."
    exit 1
fi

chown -R annestar:root "$CHROOT_DIR"

if [ "$fail" -ne 0 ]; then
    echo "Done, but some mounts could not be removed. Check 'mount | grep $CHROOT_DIR'."
    exit 1
fi

echo "Done. All chroot mounts removed."