#!/bin/bash

export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/opt/puppetlabs/bin

delay='1'   # second
timeout='2' # minutes
end_time="$(date -d "now + ${timeout} minutes" +%s)"
cachefile='/etc/zfs/zpool.cache'

zfs_ready() {
  # A pool listed in the cache file but not imported yet. Without this check
  # "no pool at all" counts as ready: the two checks below inspect the pools
  # that *are* present, and both produce empty output when there are none.
  # "zpool import -c <cache>" lists exactly the cached pools still available
  # for import and prints "no pools available to import" once all are up.
  if [ -s "$cachefile" ] && zpool import -c "$cachefile" 2>/dev/null | grep -q 'pool:'; then
    return 3
  elif zpool list -Ho health | grep -v "ONLINE" | grep -q "."; then
    return 1
  elif zfs list -Ho mountpoint,mounted | grep -Ev "^(legacy|none)\s" | grep -Fv "/lxd/storage-pools/" | grep -v "yes$" | grep -q "."; then
    return 2
  else
    return 0
  fi
}

until zfs_ready >/dev/null 2>&1; do
  if [ "$(date +%s)" -gt "$end_time" ]; then
    echo "Service zfs timed out."
    exit 1
  fi
  sleep "$delay"
done

exit 0
