#!/bin/sh

# copyright 2004 vagrant@freegeek.org, distributed under the terms of the
# GNU General Public License version 2 or any later version.

server="$nfsserver"
if [ -z "$server" ]; then
  if [ -n "$siaddr" ]; then
    echo "NOTE: assuming siaddr $siaddr is also NFS server..."
    server="$siaddr"
  elif [ -n "$tftp" ]; then
    echo "WARNING: assuming TFTP server $tftp is also NFS server..."
    server="$tftp"
  elif [ -n "$serverid" ]; then
    echo "WARNING: assuming DHCP server $serverid is also NFS server..."
    server="$serverid"
  fi
fi

# stupid hack to remove trailing whitespace
for s in $server; do
  server=$s
done

if [ -z "$server" ]; then
  echo "ERROR: no NFS server defined, exiting.."
  # FIXME: don't exit, as later scripts may still need to run
  umount_all
  exit 1
fi

nfsroot="$nfspath"
if [ -z "$fs_type" ]; then
  fs_type=nfs
fi

if [ -z "$nfs_opts" ]; then
  fs_options=ro,async,nolock
else
  fs_options="$nfs_opts"
fi

echo "attempting to mount NFS filesystem..."

modprobe nfs

do_mount() {
  command="mount -nt $1 -o $2 $3:$4 /mnt"
  echo "$command"
  $command
  return "$?"
}

test_chroot() {
  chroot "$1" /bin/true
}

warn_mount_failed() {
  echo "WARNING: mounting root failed for: $@"
  echo "NOTE: trying fallback..."
}

mount_root() {
  fs="$1"
  opts="$2"
  serv="$3"
  mount_dir="$4"
  do_mount "$fs" "$opts" "$serv" "$mount_dir" 
  status="$?"
  if [ "0" = "$status" ]; then
    # check to see that we're running the right architecture.
    test_chroot /mnt
    status=$?
    if [ "0" != "$status" ]; then
      warn_mount_failed "$serv:$mount_dir"
      if [ -n "$chroot_name" ] && [ -d "/mnt/$chroot_name" ]; then
        test_chroot "/mnt/$chroot_name"
        status=$?
        umount -n /mnt
        if [ "0" = "$status" ]; then
          do_mount "$fs" "$opts" "$serv" "$mount_dir/$chroot_name" 
          status="$?"
        fi
      else
        # umount, so that the initrd can be freed later.
        umount -n /mnt
      fi
    fi
  fi
  return $status
}

mount_root "$fs_type" "$fs_options" "$server" "$nfsroot"
status="$?"
if [ "0" != "$status" ]; then
  if [ -n "$lessdisks_path" ] && [ "$nfsroot" != "$lessdisks_path" ]; then
    warn_mount_failed "$server:$nfsroot"
    mount_root "$fs_type" "$fs_options" "$server" "$lessdisks_path/$chroot_name"
    status="$?"
  fi
fi

if [ "0" != "$status" ]; then
  echo "could not mount root, bringing up a debugging shell..."
  /bin/sh
fi

if [ "true" = "$use_devfs" ]; then
  echo "mounting devfs..."
  chroot /mnt mount -nt devfs devfs dev
else
  echo "skipping devfs mount..."
fi

if [ -z "$LESSDISKS_DEBUG" ] || [ "false" = "$LESSDISKS_DEBUG" ]; then
  umount_all
fi
