#!/usr/bin/env sh
# Convert an aax file to an m4b file
#
# Discover the activation bytes once then store as a text file and reuse.
# https://github.com/inAudible-NG/tables
#
# Usage:
#
#     ffmpeg-audible -b /path/to/activation-bytes.txt /path/to/file.aax

while getopts b:hx opt; do
    case $opt in
    b) read -r activation_bytes < "$OPTARG";;
    h) awk 'NR == 1 {next} /^$/ {exit} {print substr($0, 3)}' "$0"; exit;;
    x) set -x;;
    esac
done
shift $(( OPTIND - 1 ))

if [ -z "$activation_bytes" ]; then
    printf 'Missing activation_bytes.\n' 1>&2
    exit 1
fi

aax_file="${1:?'Audiobook required.'}"

ffmpeg \
    -activation_bytes "$activation_bytes" \
    -i "$aax_file" -vn -c:a copy "${aax_file%.aax}.m4b"
