#!/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 write Taler merchant reports to a file.
# Reads report data from stdin and writes it to a file.
#
# Usage: taler-merchant-report-generator-file -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

# 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)
    cat - > "$TARGET_ADDRESS.txt"
    ;;
  application/pdf)
    cat - > "$TARGET_ADDRESS.pdf"
    ;;
  application/json)
    cat - > "$TARGET_ADDRESS.json"
    ;;
  application/xml)
    cat - > "$TARGET_ADDRESS.xml"
    ;;
  text/csv)
    cat - > "$TARGET_ADDRESS.csv"
    ;;
  image/jpeg)
    cat - > "$TARGET_ADDRESS.jpeg"
    ;;
  image/png)
    cat - > "$TARGET_ADDRESS.png"
    ;;
  *)
    cat - > "$TARGET_ADDRESS"
    ;;
esac

exit 0
