#!/bin/bash

# Expects exactly three arguments:
# 1. Attachment file to consider.
# 2. Metadata file to write to.
# 3. Content file to write to.
# 4. Attachment internal date file to write to.

ATTF="$1"
AMDF="$2"
ACTF="$3"
AIDF="$4"
TEMPINFO=$(mktemp)
TEMPCONTENT=$(mktemp)

# Need the result files to exist for the caller.
touch "${AMDF}" "${ACTF}" "${AIDF}"

# Get the file size.
# … the sed invocation is because I like a space between the number and unit.
numfmt --to=iec-i --suffix=B $(stat --format='%s' "${ATTF}") \
    | sed 's/\([0-9\.][0-9\.]*\)\(.*\)/\1 \2/' \
    | tr -d '\n' >> "${AMDF}"

# Onto the MIME type.
/bin/echo -n ", " >> "${AMDF}"

MT=$(file --brief --mime-type "${ATTF}")

echo "${MT}" \
    | tr -d '\n' >> "${AMDF}"

# Now handle some content for particular MIME types.

if test Q"${MT}" = Qtext/plain; then
    cat "${ATTF}" > "${ACTF}"
fi

if test Q"${MT}" = Qapplication/zip; then
    unzip -v "${ATTF}" > "${ACTF}"
fi

if test Q"${MT}" = Qapplication/x-7z-compressed; then
    7z l "${ATTF}" | sed '1,/^   Date      Time   / d'  > "${ACTF}"
fi

if test Q"${MT}" = Qapplication/pdf; then
    ( echo -n ", ";
      pdfinfo "${ATTF}" | grep 'Pages:'| awk '{print $2}';
      echo " page(s)" ) \
    | tr -d '\n' >> "${AMDF}"
fi

if test Q"${MT}" = Qapplication/vnd.ms-outlook -o Q"${MT}" = Qmessage/rfc822; then
    # call ff_squish_email
    ff_squish_email "${ATTF}" "${TEMPINFO}" "${TEMPCONTENT}" "${AIDF}"
    # append the results
    echo >> "${AMDF}"
    cat "${TEMPINFO}" >> "${AMDF}"
    cat "${TEMPCONTENT}" >> "${ACTF}"
fi

rm -f "${TEMPINFO}" "${TEMPCONTENT}"

