#!/bin/sh
# $UFP$
#set -x

DIALOG_CANDIDATES="/usr/bin/dialog /usr/local/bin/cdialog /usr/bin/bsddialog /usr/local/bin/bsddialog"

for cand in ${DIALOG_CANDIDATES}; do
  if [ -e "${cand}" ]; then
    DIALOG="${cand}"
    break
  fi
done
unset cand

if [ -z "${DIALOG}" ]; then
  echo "${0}: neither of ${DIALOG_CANDIDATES} are present and executable." >/dev/stderr
  exit 69
fi

readonly DIALOG

readonly COLUMNS_MIN=6
COLUMNS=`tput cols`

if [ "${COLUMNS}" -le ${COLUMNS_MIN} ]; then
  echo "${0}: terminal isn't wide enough, only ${COLUMNS} columns wide, must be at least ${COLUMNS_MIN} wide." >/dev/stderr
  exit 70
fi

readonly LINES_MIN=8
LINES=`tput lines`

if [ "${LINES}" -le ${LINES_MIN} ]; then
  echo "${0}: terminal isn't tall enough, only ${LINES} lines tall, must be at least ${LINES_MIN} tall." >/dev/stderr
  exit 70
fi

# Assuming Unicode and UTF-8 encoding.
NBSP=`printf '\302\240'`

for wc in zroot/usr/src zroot/usr/ports; do
  list=""

  for snap in `zfs list -H -o name -t snapshot ${wc}/.git | cut -d @ -f 2`; do
    snapsizes="`zfs get -Ho value used ${wc}/.git@${snap}`${NBSP}`zfs get -Ho value used ${wc}/.git/objects@${snap}`"
    list="${list} ${snap} ${wc}/.git@${snap}${NBSP}${snapsizes} off"
  done
  unset snapsize

  listfile="/tmp/list-${$}.txt"
  ${DIALOG} --checklist "ZFS snapshots for ${wc}/.git" $((${LINES}-(${LINES_MIN}-3))) $((${COLUMNS}-${COLUMNS_MIN})) $((${LINES}+${LINES_MIN})) ${list} 2> ${listfile}

  list=`cat ${listfile}`
  rm ${listfile}

  echo
  echo

  for snap in ${list}; do
    zfs destroy -v ${wc}/.git@${snap}
    zfs destroy -v ${wc}/.git/objects@${snap}
  done
done

# EOF
