#!/bin/bash

# Declare colors, if available
if test -n "$ncolors" && test $ncolors -ge 8; then
    # Modifiers
    BOLD="$(tput bold)"
    RESET="$(tput sgr0)"

    # Colors
    RED="$(tput setaf 1)"
    WHITE="$(tput setaf 7)"
    YELLOW="$(tput setaf 226)"
fi

# Ensure we have at least 2 arguments
if (( $# < 2 )); then
    EXE_NAME=$(basename -- "$0")
    echo "Usage: ${EXE_NAME} path/to/m4b path/to/cover/image"
    exit 1
fi

# Ensure the first argument ends in m4b
if [[ ! "$1" == *.m4b ]]; then 
    echo "${RED}'${WHITE}$2${RED}' does not have an m4b extension.${RESET}"
    exit 1
fi
BOOK_FILE=$1

# Ensure the second argument is an image
if [[ ! ${2,,} =~ ^.*?(.png|.jpg|.jpeg)$ ]]; then
    echo "${RED}First argument must be a PNG or JPEG.${RESET}"
    exit
fi
COVER_FILE=$2

# Swap the cover art
ffmpeg -i "${BOOK_FILE}" -i "${COVER_FILE}" -map 0:a -map 1 -c copy -disposition:v:0 attached_pic "${BOOK_FILE%%.m4b}.new.m4b"

echo "Done!"

# vim: syntax=sh
