#!/bin/ksh
#
# $Revision: 1.1+21 $ $Date: 2024-06-10 01:08:38-04 $
# $Source: /root/backup/bin $
# $Host: hairball.my.domain $
# $UUID: 1e824133-3a22-46f3-b1b3-2697f12e979b $
#
#<doparity: make parity files for one or more archives.
# Basic messages go to syslog, details go to a logfile under /var/log/usb.
# Intended to be run like so: daemon -c /path/to/doparity
#
# It's more convenient if users in "wheel" can run this; either run it
# as root the first time, or create /var/log/usb and change the group
# ownership to "wheel".  I don't like running "sudo" from scripts, but
# you do you.

export PATH=/usr/local/bin:/bin:/usr/bin
set -o nounset
tag=${0##*/}
umask 022
PS4='${tag}-${LINENO}: '

# The output from par2xxx programs contains carriage-returns.
# This function makes the results easier to read.
cleanup () {
    scr='
        s/\r/\n/g
        /^Constructing:/d
        /^Loading:/d
        /^Scanning:/d
        /^Processing:/d
    '

    # Can't do it all in one pass; the carriage return stuff needs
    # to be done first.
    sed -e "$scr" | sed -e "/%$/d"
}

# Basic logging.
logmsg () {
    logger -t "$tag" "$@"
    echo "$(date '+%F %T.%3N%:::z') $tag: $@"
}
die () { logmsg "FATAL: $@"; exit 1; }

# Set up the detailed logfile.
set X $(date "+%Y %m %d")
case "$#" in
    4)  shift; yr=$1; mon=$2; day=$3 ;;
    *)  die "date failed, returned $@" ;;
esac

logdir="/var/log/usb/$yr"
test -d "$logdir" || mkdir -p $logdir || die "$logdir: not found"
logfile="$logdir/${mon}${day}"
touch $logfile

# Users in "wheel" should be able to run this.
if id | grep 'uid=0(root)' > /dev/null ; then
    d=$(dirname "$logdir")
    chgrp -R wheel "$d"
    find "$d" -type d -print | xargs chmod 2775
    find "$d" -type f -print | xargs chmod 664
fi

exec 1>> $logfile
exec 2>&1

# Do all the .tgz files under your backup directory.
top="/archive/bkup"
cd "$top" || die "$top: cannot cd"
logmsg start

list=$(find . -type f -name '*.tgz' -print | sort)
test -n "$list" || die "no tgz files found"

for arch in $list ; do
    d=$(dirname "$arch")
    b=$(basename "$arch")
    (
        cd $d
        logmsg "par2create -r30 $b"
        par2create -r30 $b | cleanup
        logmsg "par2verify $b.par2"
        par2verify $b.par2 | cleanup
    )
done

logmsg done
exit 0
