#!/usr/bin/env bash
# Usage: bash fade-out.sh <cut.mp3> <fade_seconds>   Fades the last N seconds of a cut to silence and writes <name>-fade.mp3 next to it (re-encodes at LAME quality 2).
set -u
in="${1:-}"; fade="$(printf '%s' "${2:-1.5}" | tr -d '\r')"
[ -n "$in" ] || { echo "usage: bash fade-out.sh <cut.mp3> <fade_seconds>"; exit 1; }
[ -f "$in" ] || { echo "missing file: $in"; exit 2; }
[ -s "$in" ] || { echo "empty file: $in"; exit 3; }
dur=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$in" | tr -d '\r')
[ -n "$dur" ] || { echo "not an audio file: $in"; exit 4; }
[[ "$fade" =~ ^[0-9]+([.][0-9]+)?$ ]] && awk -v f="$fade" 'BEGIN{exit !(f>0)}' || { echo "fade must be a number of seconds above 0, got: $fade"; exit 5; }
awk -v d="$dur" -v f="$fade" 'BEGIN{exit !(f<d)}' || { echo "fade of ${fade}s is not shorter than the file (${dur}s)"; exit 5; }
st=$(awk -v d="$dur" -v f="$fade" 'BEGIN{printf "%.3f", d-f}')
b=$(basename -- "$in"); out="$(dirname -- "$in")/${b%.*}-fade.mp3"
[ "${b%.*}" != "" ] || out="$(dirname -- "$in")/${b}-fade.mp3"
ffmpeg -v error -y -i "$in" -af "afade=t=out:st=${st}:d=${fade}" -c:a libmp3lame -q:a 2 "$out" || { echo "ffmpeg could not write $out"; exit 6; }
echo "wrote $out (fade from ${st}s for ${fade}s)"
