#!/bin/bash -

#
# Copied from a 'history' file on archive.org and turned into a script
#

set -o nounset                              # Treat unset variables as an error

SCRIPT=${0##*/}

#===  FUNCTION  ================================================================
#          NAME:  cleanup_temp
#   DESCRIPTION:  Cleanup temporary files in case of a keyboard interrupt
#                 (SIGINT) or a termination signal (SIGTERM) and at script
#                 exit
#    PARAMETERS:  * - names of temporary files to delete
#       RETURNS:  Nothing
#===============================================================================
function cleanup_temp {
    for tmp in "$@"; do
        [ -e "$tmp" ] && rm --force "$tmp"
    done
    exit 0
}

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

if [[ $# -eq 0 ]]; then
    echo "Usage: $SCRIPT audio_file"
    exit 1
fi

AUDIO="$1"
IMAGE="${AUDIO%.*}.png"

if [[ ! -e $AUDIO ]]; then
    echo "$SCRIPT: audio file $AUDIO not found"
    exit 1
fi

#
# Make  a temporary file (called /tmp/XXXX.png) and set traps to delete them
#
TMP1=$(mktemp -p /tmp XXXXXXXX.png) || {
    echo "$SCRIPT: creation of temporary file failed!"
    exit 1
}
trap 'cleanup_temp $TMP1' SIGHUP SIGINT SIGPIPE SIGTERM EXIT

#
# Make a temporary PNG file from the audio. The original uses a 'timeout' call
# but I can't get it to work for me.
#
ffmpeg -v 0 -analyzeduration 900000000000 -probesize 200M -threads 2 -i "$AUDIO" \
    -filter_complex aformat=channel_layouts=mono,showwavespic=colors=white:s=3200x800 \
    -frames:v 1 -f apng - 2>/dev/null | \
    convert - -background black -alpha remove -alpha off "$TMP1" 2>/dev/null | cat > /dev/null 2>&1

#
# Not clear what's being done to the image here, but it produces a useful end
# result, or seems to!
#
convert -background black "$TMP1" -gravity center -background black -transparent white - | \
    convert - -gravity South -background white -splice 0x5 -background black -splice 0x5 - | \
    convert - -trim - | \
    convert - -gravity South -chop 0x5 - | \
    convert - -gravity North -background white -splice 0x5 -background black -splice 0x5 - | \
    convert - -trim - | \
    convert - -gravity North -chop 0x5 - | \
    convert - -resize '800x200!' "$IMAGE"

#
# The original renamed the temporary file to be the target image file, but
# that's probably becausae part of this is done in a Docker container. Doesn't
# seem appropriate here
#

# vim: syntax=sh:ts=8:sw=4:ai:et:tw=78:fo=tcrqn21