#!/usr/bin/env bash

cleanString() {
     tr -d '"'
}

# getHash returns the hash of a given file.
function getHash() {
    echo $(xxd -p -l20 -s 653 ${1})
}

# getActivationBytes returns the bytes needed to decrypt a given hash. 
function getActivationBytes() {
    json=$(curl -A 'audible-converter' https://aax.api.j-kit.me/api/v2/activation/${1})
    echo $(echo $json | jq '.activationBytes' | cleanString)
}

# createConfig creates a config file.
function createConfig() {
    hash=$(getHash ${2})
    bytes=$(getActivationBytes $hash)
    echo "activationBytes=${bytes}" >> ${1}
}

# checkAudibleFile checks if a given file is valid and if not exits the program.
function checkAudibleFile() {
    if [ ! -f ${1} ]; then
	echo "${1}" not found
	exit 1
    fi
}

function removeDRM() {
    ffmpeg -activation_bytes ${2} -i ${1} -c copy "${3}.m4b"
}

function getChapterJSON() {
    echo $(ffprobe -i ${1} -print_format json -show_chapters -loglevel error -sexagesimal | jq '.chapters')
}

function getMetadataJSON() {
    echo $(ffprobe -show_format -print_format json ${1} | jq '.format.tags')
}

function getTitle() {
    echo $(echo ${1} | jq '.title' | cleanString)
}

function fileSafe() {
     sed -e 's/[^A-Za-z0-9._-]/-/g' | tr '[:upper:]' '[:lower:]' | sed -e 's/--/-/g'
}

settingsFile='./settings.conf'

audibleFile=${1}
checkAudibleFile $audibleFile

# Check for config file
if [ ! -f $settingsFile ]; then
    echo 'No config file'
    createConfig $settingsFile $audibleFile
fi

# Load settings
. $settingsFile

metadataJSON=$(getMetadataJSON $audibleFile)
chapterJSON=$(getChapterJSON $audibleFile)
name=$(getTitle "${metadataJSON}" | fileSafe)

if [ ! -f "${name}.m4b" ]; then
    removeDRM $audibleFile $activationBytes $name
fi

mkdir -p $name

data=$(echo "${chapterJSON}" | jq '.[] | "\(.start),\(.end),\(.tags.title)"')
echo $data
IFS=' ' read -r -a array <<< "$data"


echo $(echo "${chapterJSON}" | jq '.[] | .start,.end,.tags.title')