#!/bin/bash

set -euo pipefail

sed -ri 's|^(.+ /ngcp-fallback .+) ro,(.+)$|\1 \2|' /etc/fstab

umount /ngcp-fallback/proc      || true
umount /ngcp-fallback/sys       || true
umount /ngcp-fallback/dev/pts   || true
umount /ngcp-fallback/dev       || true
umount /ngcp-fallback/run/udev  || true
umount /ngcp-fallback/ngcp-data || true

if ! umount /ngcp-fallback; then
  echo "ERROR: Failed to unmount /ngcp-fallback."

  echo -e "### lsof output: open files under /ngcp-fallback ###"
  lsof +D /ngcp-fallback/ > /tmp/lsof.err || true
  # Check if lsof.err is empty or not
  if [[ -s /tmp/lsof.err ]] ; then
    cat /tmp/lsof.err
    rm /tmp/lsof.err
  else
    echo "No open files found."
  fi

  echo -e "\n### fuser output: processes using /ngcp-fallback ###"
  fuser -vm /ngcp-fallback || echo "No processes found."

  echo -e "\n### Processes with current working directory or root in /ngcp-fallback ###"
  # shellcheck disable=SC2010
  for pid in $(ls /proc/ | grep -E '^[0-9]+$'); do
    cwd=$(readlink -e "/proc/$pid/cwd" 2>/dev/null || true)
    root=$(readlink -e "/proc/$pid/root" 2>/dev/null || true)
    if [[ "${cwd:-}" == /ngcp-fallback* || "${root:-}" == /ngcp-fallback* ]]; then
      echo "PID $pid uses /ngcp-fallback (cwd: $cwd, root: $root)"
      ps -p "$pid" -o pid,ppid,cmd --no-headers
    fi
  done

  echo -e "\n### !!! Aborting script due to failed unmount! !!! ###"
  exit 1
fi

mkfs.ext4 -F "${TO_PARTITION}"
mount "${TO_PARTITION}" /ngcp-fallback
