#!/usr/bin/env python3
import locale
import shlex
from subprocess import Popen, PIPE


def pslurp(cmdline):
    return [line.decode("utf-8", errors="ignore").split() for line in Popen(shlex.split(cmdline), stdout=PIPE).stdout]


def get_bytes_free():
    # Use df to get number of bytes free
    df_out = pslurp("df -B 1 .")
    free_line = df_out[-1]

    # Probably a better way to detect the file system, but this works too:
    file_system = free_line[0]

    # Special case AFS: get number of bytes remaining in quota with `fs`
    if file_system == "AFS":
        fs_lq_out = pslurp("fs lq")
        quota_line = fs_lq_out[-1]
        quota = int(quota_line[1])
        used = int(quota_line[2])
        bytes_free = (quota - used) * 1024

    # Special case CEPH: get number of bytes remaining in quota with `getfattr`
    elif file_system == "ceph-fuse":
        used = int(pslurp("getfattr --only-values -n ceph.dir.rbytes .")[0][0])
        quota = int(pslurp("getfattr --only-values -n ceph.quota.max_bytes .")[0][0])
        bytes_free = quota - used

    else:
        bytes_free = int(free_line[3])

    return bytes_free


locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
print("%19s bytes free" % locale.format_string("%d", get_bytes_free(), True))
