#!/bin/sh -e

set -u

usage() {
  cat <<EOF
Usage: $(basename "$0") <input.pdf>

Convert a PDF file to EPUB format using pdftotext and pandoc.

Arguments:
    input.pdf    The PDF file to convert

The output will be created in the same directory as the input file,
with the same name but .epub extension.
EOF
}

# check if we have all required commands
for cmd in pdftotext pandoc; do
  if ! command -v "${cmd}" >/dev/null 2>&1; then
    echo "Error: Required command '${cmd}' not found"
    exit 1
  fi
done

# check arguments
if [ "$#" -ne 1 ]; then
  usage
  exit 1
fi

input_file="$1"

# check if input file exists and is readable
if [ ! -f "${input_file}" ]; then
  echo "Error: Input file '${input_file}' does not exist"
  exit 1
fi

if [ ! -r "${input_file}" ]; then
  echo "Error: Input file '${input_file}' is not readable"
  exit 1
fi

# check if input file is a PDF
if ! file "${input_file}" | grep -q "PDF document"; then
  echo "Error: Input file '${input_file}' is not a PDF document"
  exit 1
fi

# get the base name without extension
basename="${input_file%.*}"
output_file="${basename}.epub"

# create temporary directory
temp_dir=$(mktemp -d)
trap 'rm -rf "$temp_dir"' EXIT

# use original filename (without extension) for intermediate text
filename=$(basename "${input_file}")
basename="${filename%.*}"
temp_file="${temp_dir}/${basename}.txt"

echo "Converting PDF to text..."
if ! pdftotext "${input_file}" "${temp_file}"; then
  echo "Error: Failed to convert PDF to text"
  exit 1
fi

echo "Converting text to EPUB..."
if ! pandoc "${temp_file}" --metadata title="${basename}" -o "${output_file}"; then
  echo "Error: Failed to convert text to EPUB"
  exit 1
fi

echo "Successfully created: ${output_file}"
