#!/bin/sh

# 10GB autofill
max_size=10485760
check_size=no
blocksize=512M
dry_run=no

error() {
  echo "$@" 1>&2
}
fatal() {
  error "$@"
  exit 1
}

usage() {
    cat >/dev/stderr <<EOF
usage: $0 [ options ] [ <outputdir> ...]" 1>2
	will fill <outputdir> with an empty file (and remove that file)"

        if no outputdir is given, all local filesystems are filled
        (with less free space than ${max_size}kB are considered)"

OPTIONS
        -h : print this help
        -n : dry-run (the file is created/removed but not filled)
EOF
    exit $1
}

getblocks() {
    local bs=$2
    local blocks=$(df -B"${bs}" "$1" | tail -1 | awk '{print $4}')
    blocks=$((blocks-1))
    [ ${blocks} -gt 0 ] || blocks=1
    echo $blocks
}

fillit() {
    local outdir="$1"
    local size
    local blocks

    if [ "x${check_size}" = "xyes" ]; then
        size=$(df -P "${outdir}" | egrep "^/" | sed -e 's/[[:space:]]*[0-9][0-9]*%.*//' | awk '{print $NF}')
        if [ ${size} -gt ${max_size} ]; then
            error "skipping ${outdir} - too much to fill (${size}kB > ${max_size}kB)"
            return 1
        fi
    fi

    if [ -d "${outdir}" ]; then
        outfile=$(mktemp -p "${outdir}")
    else
        if [ -e "${outfile}" ]; then
            error "refusing to overwrite existing file: ${outfile}"
            return 1
        fi
    fi

    blocks=$(getblocks "${outfile}" ${blocksize})
    error "filling ${outdir} ($(df -h ${outdir} | tail -1 | awk '{print $4}') = ${blocks}*${blocksize})"
    touch "${outfile}" 2>/dev/null || (error "unable to create ${outfile}"; return 1)

    if [  "x${dry_run}" = "xyes" ]; then
        error "DRY RUN: skipping fill of ${outdir}"
    else
        dd status=progress if=/dev/zero of="${outfile}" bs=${blocksize} count=${blocks}
    fi
    rm "${outfile}"
}


while getopts "hn" opt; do
    case $opt in
        h)
            usage
            ;;
        n)
            dry_run=yes
            ;;
        \?)
            usage 1
            ;;
    esac
done

shift $(( ${OPTIND} - 1 ))

if [ $# -lt 1 ]; then
    check_size=yes
    for d in $(lsblk -nlo type,mountpoint | egrep "^part /" | cut -f2 -d' ' | sort -u); do
        fillit "$d"
        echo ""
    done
else
    for d in "$@"; do
        fillit "$d"
        echo ""
    done
fi
