{ pkgs }:

pkgs.writeShellScriptBin "my-rebuild" ''
BOOT=/boot
ATTEMPTS=5
is_mounted(){
  ${pkgs.util-linux}/bin/findmnt --mountpoint $BOOT
  return $?
}

mount_boot(){
  echo "mounting $BOOT..."
  mount $BOOT 2> /dev/null
  return $?
}

umount_boot(){
  echo "umounting $BOOT..."
  umount $BOOT
  return $?
}

try_mount(){
  attempt=0

  while [[ attempt -ne 5 ]]
  do
    mount_boot
    res1=$?
    is_mounted
    res2=$?
    if [[ $res1 -eq 0 && $res2 -eq 0 ]]; then
      echo "Mounted $BOOT!"
      return 0
    fi
    echo "Failed to mount $BOOT, waiting..."
    attempt=$(($attempt+1))
    sleep 2
  done
  return 1
}

if [[ $EUID -ne 0 ]]; then
  echo "Must be a superuser!"
  exit 1
fi

try_mount
if [[ $? -ne 0 ]]; then
  echo "Failed to mount $BOOT!"
  exit 1
fi
echo "Rebuilding..."
nixos-rebuild $@
sleep 2
echo "Done rebuild!"
umount_boot
''