#!/bin/bash
#
# Clean up any holders / mounts / LVM / crypt devices on the install disk
# before archinstall starts wiping. Idempotent — called once per install attempt
# from the orchestrator's cleanup_disk phase.
#
# Ported verbatim from .automated_script.sh's cleanup_install_disk(). Kept in
# bash because lsblk / findmnt / lvm / cryptsetup are all easier to drive
# here than from Python.

set -uo pipefail

if [[ ${1:-} == --protected ]]; then
  target="${2:-}"
  [[ -n $target ]] || { echo "Usage: $0 --protected <target>" >&2; exit 1; }
  findmnt -R "$target" >/dev/null 2>&1 && umount -R "$target" || true
  exit 0
fi

disk="${1:-}"
[[ -n $disk && -b $disk ]] || { echo "Need a block device argument; got '$disk'" >&2; exit 1; }

echo "Cleaning up existing holders on install disk: $disk"
findmnt -R /mnt >/dev/null && umount -R /mnt || true

while read -r dev; do
  [[ -b $dev ]] || continue
  swapoff "$dev" 2>/dev/null || true
  while read -r target; do
    [[ -n $target ]] && umount "$target" 2>/dev/null || true
  done < <(findmnt -rn -S "$dev" -o TARGET 2>/dev/null || true)
done < <(lsblk -rnpo PATH "$disk")

while read -r dev type; do
  [[ $type == disk || $type == part || $type == crypt ]] || continue
  while read -r vg; do
    [[ -n $vg ]] && vgchange -an "$vg" 2>/dev/null || true
  done < <(pvs --noheadings -o vg_name "$dev" 2>/dev/null | awk '{$1=$1; print}' | sort -u)
done < <(lsblk -rnpo PATH,TYPE "$disk")

while read -r dev type; do
  [[ $type == crypt ]] && cryptsetup close "$dev" 2>/dev/null || true
done < <(lsblk -rnpo PATH,TYPE "$disk")

blockdev --flushbufs "$disk" 2>/dev/null || true
partprobe "$disk" 2>/dev/null || true
udevadm settle || true
