#!/bin/bash

# Copyright (C) 2013-2025 Marcin Krol <hawk@tld-linux.org>
# All Rights Reserved

# if no args specified show usage info
if [ "${1}" = "" ]; then
  echo "Usage: $(basename "${0}" 2>/dev/null) <destination path>"
  exit 1
fi

# allow only absolute destination paths
if ! echo "${1}" | grep -E -q "^/"; then
  echo "^[[1;31mError:^[[0m please use absolute path as destination"
  exit 1
fi

# check if destination path exist and bail out if not
if ! [ -d "${1}" ]; then
  echo "^[[1;31mError:^[[0m bad destination path specified"
  exit 1
fi

# bind-mount /dev, /proc, /run, /sys
for d in dev proc run sys; do
  if ! [ -d "${1}/${d}" ]; then
    mkdir -p "${1}/${d}" 1>/dev/null 2>&1
  fi
  mount /${d} "${1}/${d}" -o bind 1>/dev/null 2>&1
done
# bind-mount efivars if running under EFI
if [ -d "/sys/firmware/efi" ]; then
  mount /sys/firmware/efi/efivars "${1}/sys/firmware/efi/efivars" -o bind 1>/dev/null 2>&1
fi

# chroot into destination dist
chroot "${1}" su -

# umount efivars if running under EFI
if [ -d "/sys/firmware/efi" ]; then
  umount "${1}/sys/firmware/efi/efivars" 1>/dev/null 2>&1
fi
# umount /dev, /proc, /run, /sys from destination path
for d in sys run proc dev; do
  mountpoint -q "${1}/${d}" 1>/dev/null 2>/dev/null
  result=$?
  if [ "${result}" -eq 0 ]; then
    umount "${1}/${d}" 1>/dev/null 2>&1
  fi
done
