#!/bin/bash
#
# This file is part of TALER
# Copyright (C) 2025 Taler Systems SA
#
# TALER is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; either version 3, or (at your option) any later version.
#
# TALER is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
#

#
# Script to email Taler merchant reports using the UNIX mail command.
# Reads report data from stdin and sends it via email with appropriate formatting.
#
# Usage: taler-merchant-report-generator-email -d DESCRIPTION -m MIME_TYPE -t TARGET_ADDRESS
#

set -eu

DESCRIPTION=""
MIME_TYPE=""
TARGET_ADDRESS=""
TMPDIR="${TMPDIR:-/tmp}"

while getopts "d:m:t:h" opt; do
  case $opt in
    d)
      DESCRIPTION="$OPTARG"
      ;;
    m)
      MIME_TYPE="$OPTARG"
      ;;
    t)
      TARGET_ADDRESS="$OPTARG"
      ;;
    h)
      echo "Usage: $0 -d DESCRIPTION -m MIME_TYPE -t EMAIL_ADDRESS"
      echo ""
      echo "Sends reports via email."
      echo ""
      echo "Options:"
      echo "  -d DESCRIPTION      Subject line for the email"
      echo "  -m MIME_TYPE        MIME type of the report (e.g., text/plain, application/pdf)"
      echo "  -t EMAIL_ADDRESS    Email address to send the report to"
      echo "  -h                  Show this help message"
      echo ""
      echo "The report data is read from stdin."
      exit 0
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      echo "Use -h for help" >&2
      exit 1
      ;;
  esac
done

if [ -z "$DESCRIPTION" ];
then
  echo "Error: Description (-d) is required" >&2
  exit 1
fi

if [ -z "$MIME_TYPE" ];
then
  echo "Error: MIME type (-m) is required" >&2
  exit 1
fi

if [ -z "$TARGET_ADDRESS" ];
then
  echo "Error: Target address (-t) is required" >&2
  exit 1
fi

# Validate email address format (basic check)
if ! echo "$TARGET_ADDRESS" | grep -qE '^[^@]+@[^@]+\.[^@]+$';
then
  echo "Error: Invalid email address format: $TARGET_ADDRESS" >&2
  exit 1
fi

if ! command -v mail >/dev/null 2>&1;
then
  echo "Error: 'mail' command not found." >&2
  exit 1
fi
if ! command -v uuencode >/dev/null 2>&1;
then
  echo "Error: 'uuencode' command not found." >&2
  exit 1
fi

# Normalize MIME type to lowercase for comparison
MIME_TYPE=$(echo "$MIME_TYPE" | tr '[:upper:]' '[:lower:]')

# Handle different MIME types
case "$MIME_TYPE" in
  text/plain)
    # For plain text, send directly as email body
    mail -s "$DESCRIPTION" "$TARGET_ADDRESS"
    ;;

  *)
    # For all other MIME types, create a MIME attachment
    # Create temporary files
    TMPFILE=$(mktemp "$TMPDIR/taler-report.XXXXXX")
    MIMEFILE=$(mktemp "$TMPDIR/taler-mime.XXXXXX")

    # Ensure cleanup on exit
    trap "rm -f '$TMPFILE' '$MIMEFILE'" EXIT

    # Save stdin to temporary file
    cat - > "$TMPFILE"

    # Determine file extension based on MIME type
    case "$MIME_TYPE" in
      application/pdf)
        EXT="pdf"
        ;;
      application/json)
        EXT="json"
        ;;
      text/html)
        EXT="html"
        ;;
      text/csv)
        EXT="csv"
        ;;
      application/xml)
        EXT="xml"
        ;;
      application/zip)
        EXT="zip"
        ;;
      image/png)
        EXT="png"
        ;;
      image/jpeg)
        EXT="jpg"
        ;;
      *)
        EXT="dat"
        ;;
    esac

    FILENAME="report.$EXT"

    # Use uuencode method (works with traditional mail command)
    uuencode "$TMPFILE" "$FILENAME" | mail -s "$DESCRIPTION" "$TARGET_ADDRESS"
    ;;
esac

exit 0