1
0
angie-conv-image/scripts/static-compress.sh

66 lines
1.6 KiB
Bash
Raw Normal View History

2024-07-11 13:37:35 +03:00
#!/bin/sh
set -f
COMPRESS_MIN_RATIO=90
if command -V gzip >/dev/null ; then has_gzip=1 ; fi
if command -V brotli >/dev/null ; then has_brotli=1 ; fi
if command -V zstd >/dev/null ; then has_zstd=1 ; fi
do_gzip() { [ -s "$1.gz" ] || gzip -1kf "$1" ; comp_fixup "$1" "$1.gz" ; }
do_brotli() { [ -s "$1.br" ] || brotli -1kf "$1" ; comp_fixup "$1" "$1.br" ; }
do_zstd() { [ -s "$1.zst" ] || zstd -q1kf "$1" ; comp_fixup "$1" "$1.zst" ; }
comp_fixup() {
size1=$(env stat -c '%s' "$1") || return
[ -f "$2" ] || return
[ -s "$2" ] || { rm -f "$2" ; return ; }
size2=$(env stat -c '%s' "$2") || return
pow1=${#size1} ; pow2=${#size2}
## if size2 is _longer_ than size1 - compression did something wrong (file is bigger)
if [ ${pow2} -gt ${pow1} ] ; then
rm -f "$2" ; return
fi
## if size1 is _longer_ size2 more than 2 digits - compression was done very successful
## doubtful but okay (c) Oleg Tinkov
if [ $(( pow1 - pow2 )) -gt 2 ] ; then
return
fi
## math hack!
if [ ${pow1} -gt 7 ] ; then
skew=$(( pow1 - 4 ))
pow1=$(( pow1 - skew ))
pow2=$(( pow2 - skew ))
size1=$(printf '%s' "${size1}" | cut -c 1-${pow1})
size2=$(printf '%s' "${size2}" | cut -c 1-${pow2})
fi
ratio=$(( (100 * size2) / size1 ))
if [ ${ratio} -ge ${COMPRESS_MIN_RATIO} ] ; then
rm -f "$2"
else
## seems to be excessive
: touch -r "$1" -m "$2"
fi
}
for i ; do
[ -n "$i" ] || continue
case "$i" in
*.br | *.gz | *.zst ) continue ;;
esac
[ -f "$i" ] || continue
[ -s "$i" ] || continue
[ -z "${has_gzip}" ] || do_gzip "$i"
[ -z "${has_brotli}" ] || do_brotli "$i"
[ -z "${has_zstd}" ] || do_zstd "$i"
done