#!/bin/bash
# vim: shiftwidth=4 tabstop=4 expandtab

LIB_DIR="$( realpath "$( dirname "$( realpath "$0" )" )/../lib/ee-postfix-tools" )"
if [[ -e "$LIB_DIR/common" ]]; then
    # shellcheck source=/dev/null
    source "$LIB_DIR/common"
else
    echo "Failed to load ee-postfix-tools common lib"
    exit 1
fi

# shellcheck disable=SC2034
EXTRA_SHORT_USAGE="[email IDs] [bkp desc]"
# shellcheck disable=SC2317,SC2329
function handle_extra_args() {
    if [[ $# -lt 1 ]]; then
        usage
    elif [[ $# -ge 2 ]]; then
        DESC="${*: -1}"
        IDS=( "${@:1:$#-1}" )
    else
        IDS=( "$@" )
        DESC=""
    fi
}
handle_args "$@"
[[ ${#IDS[@]} -eq 0 ]] && usage

# Create backup directory
if [[ ! -d "$BACKUP_DIRECTORY_PATH" ]]; then
    mkdir "$BACKUP_DIRECTORY_PATH" || \
        fatal_error "Failed to backup directory ($BACKUP_DIRECTORY_PATH)!"
fi

# Compute backup file path
bkp_path="$BACKUP_DIRECTORY_PATH/$(date +%Y%m%d-%H%M%S)-"
if [[ -n "$DESC" ]]; then
    bkp_path+="$( tr ' ' '-' <<< "$DESC" | sed 's/[^a-z0-9@\.\_\-]//ig' )"
else
    bkp_path+="$( implode "-" "${IDS[@]}" )"
fi


function failure() {
    rm -f "$bkp_path"
    fatal_error "$@"
}

# Backup emails
echo -e "\x01\x01\x01\x01" > "$bkp_path"
for ID in "${IDS[@]}"; do
    run_postfix_command postcat -qbh "$ID" >> "$bkp_path" || \
        failure "Failed to retrieve mail $ID content"
    echo -e "\x01\x01\x01\x01" >> "$bkp_path"
    echo -e "\x01\x01\x01\x01" >> "$bkp_path"
done

# Compress
gzip "$bkp_path" || failure "Failed to compress backup"

info "Mail(s) ${IDS[*]} backuped in ${bkp_path}.gz. Use the following command to consult it:\n  mutt -R -m mbox -f $TEMPFILE"
