#!/bin/bash

if tty -s > /dev/null 2>&1
then
    on_tty=True
else
    on_tty=False
fi

# On MacOS, xz and others live in /usr/local/bin from homebrew.
export PATH="$PATH":/usr/local/bin

if type -path gfind > /dev/null 2>&1
then
    find='gfind'
else
    find='find'
fi

if type -path gxargs > /dev/null 2>&1
then
    xargs='gxargs'
else
    xargs='xargs'
fi

function v
{
    case "$on_tty" in
        True)
            echo -v
            ;;
        False)
            echo
            ;;
        *)
            echo "$0: internal error: \$on_tty has a strange value: $on_tty" 1>&2
            exit 1
            ;;
    esac
}

# delete any ssh wrapper files that're older than 90 days old
# shellcheck disable=SC2046
"$find" /var/tmp -maxdepth 1 -name 'hcm-*-*' -atime +90 -print0 | "$xargs" --null --no-run-if-empty rm $(v)

if ! cd ~/.hcm/logs
then
    echo "$0: cd ~/.hcm/logs failed" 1>&2
    exit 1
fi

# We're transitioning from xz to zst, because althought zst doesn't pack files quite as small, it's /Much/ faster than xz.
# compress (hard) anything that's over 30 days old
# shellcheck disable=SC2046
"$find" . -name '*.xz' -print0 | "$xargs" --null --no-run-if-empty xz --decompress $(v)
# shellcheck disable=SC2046
"$find" . -name '*.zst' -prune -o -type f -mtime +30 -print0 | "$xargs" --null --no-run-if-empty zstd --rm $(v)