#!/usr/bin/env bash
# ProCharts "Email Slides" helper for Linux (installed per user by install.sh, no root).
#
# The plugin cannot start programs, but the editor hands URLs of unknown schemes to the
# system (xdg-open). install.sh registers this script for the scheme procharts-mail only
# (a .desktop file + `xdg-mime default ... x-scheme-handler/procharts-mail`); the user's
# mailto / default-application associations are never changed.
#
#   procharts-mail 'procharts-mail:?file=<abs path>&subject=<text>&token=<id>'
#       opens a new message in the DEFAULT mail application (xdg-mime query default
#       x-scheme-handler/mailto) with the file attached:
#         Thunderbird (Betterbird, Icedove)   <client> -compose "subject='..',body='..',attachment='file://..'"
#         KMail                               kmail --subject .. --body .. --attach <file>
#         Claws Mail                          claws-mail --compose <mailto> --attach <file>
#         Evolution, Geary, other mail apps   xdg-email --subject .. --body .. --attach <file>
#         a web browser / webmail (cannot take an attachment): the mailto: compose with the
#         subject and a body naming the file, and the file is shown in the file manager
#         (org.freedesktop.FileManager1.ShowItems, else the folder is opened) to drag it in
#   procharts-mail 'procharts-mail:?reveal=<abs path>'   shows that file in the file manager
#
# Input is checked: the file must be a regular .pptx file (not a link) directly inside the
# configured send folder, written in the last minutes; texts lose control characters, Unicode
# direction / zero-width marks, quotes and commas. Nothing is evaluated; every argument is
# passed as one quoted word. The checked file is copied (never following links) into a private
# folder (~/.local/share/procharts/outbox/<random>/, mode 700) and that copy is attached, so the
# attachment cannot change after the check. Calls closer than 3 s to the previous one are
# ignored (answer "error busy"). The webmail message names the file, never its local path.
# The answer for the plugin goes to <send folder>/.ack/<token> ("ok attached <client>",
# "ok webmail", "error <reason>"); a log is kept in ~/.local/share/procharts/mail.log.
#
# Settings: ~/.local/share/procharts/mail.conf (written by install.sh), lines key=value:
#   send_dir=<folder>     the only folder files may come from (required)
#   reveal=auto|xdg-open  how to show a file (auto: the file manager's D-Bus API first)
#   max_age_minutes=15    how recent the file must be
#   min_interval_seconds=3  calls closer than this to the previous one are ignored
# PROCHARTS_MAIL_DRY_RUN=1 prints the commands (one per line, arguments separated by TAB)
# instead of running them (tests).
set -u
umask 077

DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
APP_DIR="$DATA_HOME/procharts"
LOG="$APP_DIR/mail.log"
CONF="$APP_DIR/mail.conf"
DRY="${PROCHARTS_MAIL_DRY_RUN:-}"
mkdir -p -m 700 "$APP_DIR" 2>/dev/null

log() { printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" >> "$LOG" 2>/dev/null; }
if [ -f "$LOG" ] && [ "$(stat -c %s -- "$LOG" 2>/dev/null || echo 0)" -gt 262144 ]; then
  tail -n 1000 -- "$LOG" > "$LOG.tmp" 2>/dev/null && mv -f -- "$LOG.tmp" "$LOG"
fi

SEND_DIR=""
REVEAL="auto"
MAX_AGE_MIN=15
MIN_INTERVAL=3
if [ -f "$CONF" ]; then
  while IFS='=' read -r key value || [ -n "$key" ]; do
    case "$key" in
      send_dir) SEND_DIR="$value" ;;
      reveal) case "$value" in auto|xdg-open) REVEAL="$value" ;; esac ;;
      max_age_minutes) [[ "$value" =~ ^[0-9]{1,5}$ ]] && MAX_AGE_MIN="$value" ;;
      min_interval_seconds) [[ "$value" =~ ^[0-9]{1,4}$ ]] && MIN_INTERVAL="$value" ;;
    esac
  done < "$CONF"
fi

# ------------------------------------------------------------------ helpers
# run a program detached (or print it in dry-run mode)
run() {
  if [ -n "$DRY" ]; then (IFS=$'\t'; printf 'RUN\t%s\n' "$*"); return 0; fi
  log "run: $*"
  if command -v setsid >/dev/null 2>&1; then setsid -f "$@" >/dev/null 2>&1 < /dev/null
  else "$@" >/dev/null 2>&1 < /dev/null & fi
}
# run and wait (for calls whose result matters)
run_wait() {
  if [ -n "$DRY" ]; then (IFS=$'\t'; printf 'RUN\t%s\n' "$*"); return 0; fi
  log "run: $*"
  timeout 5 "$@" >/dev/null 2>&1 < /dev/null
}
# %XX decoding without eval: only \\ and \xHH reach printf %b
urldecode() {
  local s="$1"
  s="${s//\\/\\\\}"
  s="${s//%/\\x}"
  printf '%b' "$s"
}
# percent-encoding (UTF-8 bytes); $2=keep-slash keeps '/'
pctenc() {
  local LC_ALL=C s="$1" out="" c n i
  for ((i = 0; i < ${#s}; i++)); do
    c="${s:i:1}"
    case "$c" in
      [A-Za-z0-9._~-]) out+="$c" ;;
      /) if [ "${2:-}" = keep-slash ]; then out+="/"; else out+="%2F"; fi ;;
      *) printf -v n '%d' "'$c"; printf -v c '%%%02X' "$((n & 255))"; out+="$c" ;;
    esac
  done
  printf '%s' "$out"
}
fileurl() { printf 'file://%s' "$(pctenc "$1" keep-slash)"; }
# one line of plain text: no control characters, no Unicode direction / zero-width marks
# (U+200B-U+200F, U+202A-U+202E, U+2066-U+2069), no quotes or commas that could end a
# Thunderbird value (a comma becomes ';', as in "slides 1; 3-4")
BIDI=($'\xe2\x80\x8b' $'\xe2\x80\x8c' $'\xe2\x80\x8d' $'\xe2\x80\x8e' $'\xe2\x80\x8f'
  $'\xe2\x80\xaa' $'\xe2\x80\xab' $'\xe2\x80\xac' $'\xe2\x80\xad' $'\xe2\x80\xae'
  $'\xe2\x81\xa6' $'\xe2\x81\xa7' $'\xe2\x81\xa8' $'\xe2\x81\xa9')
clean_text() {
  local s="$1" b
  s="${s//[[:cntrl:]]/ }"
  for b in "${BIDI[@]}"; do s="${s//"$b"/}"; done
  s="${s//\'/$'\xe2\x80\x99'}"
  s="${s//\"/$'\xe2\x80\x9d'}"
  s="${s//,/;}"
  printf '%s' "${s:0:200}"
}

TOKEN=""
ack() {
  [ -n "$TOKEN" ] && [ -n "$SEND_DIR" ] && [ -d "$SEND_DIR" ] || return 0
  mkdir -p -- "$SEND_DIR/.ack" 2>/dev/null && printf '%s\n' "$*" > "$SEND_DIR/.ack/$TOKEN" 2>/dev/null
}
fail() { log "error: $*"; ack "error $1"; exit 2; }

# the checked, resolved file: a regular .pptx directly inside SEND_DIR ($2=recent: written lately)
FILE=""
check_file() {
  local f="$1" real dir now mt
  [ -n "$SEND_DIR" ] || fail no-config "send_dir is not set in $CONF"
  [[ "$f" == /* ]] || fail bad-file "not an absolute path"
  [[ "$f" =~ [[:cntrl:]] ]] && fail bad-file "control characters in the path"
  shopt -s nocasematch
  if [[ "$f" != *.pptx ]]; then shopt -u nocasematch; fail bad-file "not a .pptx file: $f"; fi
  shopt -u nocasematch
  [ -L "$f" ] && fail bad-file "a symbolic link: $f"
  [ -f "$f" ] && [ -s "$f" ] || fail bad-file "missing or empty: $f"
  real="$(realpath -e -- "$f")" || fail bad-file "cannot resolve: $f"
  dir="$(realpath -e -- "$SEND_DIR")" || fail bad-file "send folder missing: $SEND_DIR"
  [ "$(dirname -- "$real")" = "$dir" ] || fail bad-file "outside $SEND_DIR: $f"
  if [ "${2:-}" = recent ]; then
    now="$(date +%s)"; mt="$(stat -c %Y -- "$real")" || fail bad-file "cannot stat: $f"
    [ $((now - mt)) -le $((MAX_AGE_MIN * 60)) ] || fail old-file "older than $MAX_AGE_MIN minutes: $f"
  fi
  FILE="$real"
}

# Shows a file in the file manager (selected), else opens its folder.
reveal() {
  local uri
  uri="$(fileurl "$1")"
  if [ "$REVEAL" = auto ] && command -v dbus-send >/dev/null 2>&1; then
    run_wait dbus-send --session --print-reply --reply-timeout=4000 --dest=org.freedesktop.FileManager1 \
      /org/freedesktop/FileManager1 org.freedesktop.FileManager1.ShowItems "array:string:$uri" "string:" && return 0
  fi
  run xdg-open "$(dirname -- "$1")"
}

# desktop file of a desktop id (user, system, Flatpak and Snap exports)
find_desktop() {
  local id="$1" d
  local IFS=:
  for d in "$DATA_HOME" ${XDG_DATA_DIRS:-/usr/local/share:/usr/share} "$HOME/.local/share/flatpak/exports/share" \
    /var/lib/flatpak/exports/share /var/lib/snapd/desktop; do
    if [ -n "$d" ] && [ -f "$d/applications/$id" ]; then printf '%s' "$d/applications/$id"; return 0; fi
  done
  return 1
}
# the Exec= command of a desktop file as words, without field codes (%u, @@u ...)
EXEC=()
read_exec() {
  local line w
  EXEC=()
  line="$(awk '/^\[/{g=($0=="[Desktop Entry]")} g && /^Exec=/{sub(/^Exec=/,""); print; exit}' "$1" 2>/dev/null)"
  [ -n "$line" ] || return 1
  read -r -a words <<< "$line"
  for w in "${words[@]}"; do
    case "$w" in %?|@@u|@@|@@*) ;; *) w="${w#\"}"; w="${w%\"}"; EXEC+=("$w") ;; esac
  done
  [ "${#EXEC[@]}" -gt 0 ]
}

# ------------------------------------------------------------------ input
URL="${1:-}"
[[ "$URL" == procharts-mail:* ]] || { log "error: not a procharts-mail URL"; exit 2; }
QUERY="${URL#procharts-mail:}"
QUERY="${QUERY#//}"
QUERY="${QUERY#\?}"
ARG_FILE="" ARG_SUBJECT="" ARG_REVEAL=""
IFS='&' read -r -a PARTS <<< "$QUERY"
for p in "${PARTS[@]}"; do
  k="${p%%=*}"; v=""
  [ "$k" != "$p" ] && v="${p#*=}"
  case "$k" in
    file) ARG_FILE="$(urldecode "$v")" ;;
    subject) ARG_SUBJECT="$(urldecode "$v")" ;;
    reveal) ARG_REVEAL="$(urldecode "$v")" ;;
    token) [[ "$v" =~ ^[A-Za-z0-9]{1,40}$ ]] && TOKEN="$v" ;;
  esac
done

# rate limit: one mail (or one reveal) per MIN_INTERVAL seconds
STAMP="$APP_DIR/last-mail"
[ -n "$ARG_REVEAL" ] && STAMP="$APP_DIR/last-reveal"
NOW="$(date +%s)"
if [ "$MIN_INTERVAL" -gt 0 ] && [ -f "$STAMP" ]; then
  LAST="$(stat -c %Y -- "$STAMP" 2>/dev/null || echo 0)"
  if [ $((NOW - LAST)) -lt "$MIN_INTERVAL" ] && [ "$LAST" -le "$NOW" ]; then
    log "ignored: another call $((NOW - LAST)) s ago"
    ack "error busy"
    exit 3
  fi
fi
touch -- "$STAMP" 2>/dev/null

# housekeeping: answers older than an hour, files sent and private copies older than 14 days
if [ -n "$SEND_DIR" ] && [ -d "$SEND_DIR" ] && [ -z "$DRY" ]; then
  chmod 700 -- "$SEND_DIR" 2>/dev/null
  find "$SEND_DIR/.ack" -maxdepth 1 -type f -mmin +60 -delete 2>/dev/null
  find "$SEND_DIR" -maxdepth 1 -type f -iname '*.pptx' -mtime +14 -delete 2>/dev/null
  find "$APP_DIR/outbox" -mindepth 1 -maxdepth 1 -type d -mtime +14 -exec rm -rf -- {} + 2>/dev/null
fi

if [ -n "$ARG_REVEAL" ]; then
  check_file "$ARG_REVEAL"
  log "reveal $FILE"
  reveal "$FILE"
  exit 0
fi

check_file "$ARG_FILE" recent
NAME="$(basename -- "$FILE")"
# the attachment: a private copy (mode 700 folder, the copy never follows a link)
mkdir -p -m 700 -- "$APP_DIR/outbox" || fail no-copy "cannot create $APP_DIR/outbox"
OUTBOX="$(mktemp -d -- "$APP_DIR/outbox/XXXXXXXX")" || fail no-copy "cannot create a folder in $APP_DIR/outbox"
cp -P --preserve=timestamps -- "$FILE" "$OUTBOX/$NAME" || fail no-copy "cannot copy $FILE"
[ -f "$OUTBOX/$NAME" ] && [ ! -L "$OUTBOX/$NAME" ] || fail no-copy "the copy is not a regular file"
COPY="$OUTBOX/$NAME"
SUBJECT="$(clean_text "${ARG_SUBJECT:-${NAME%.*}}")"
BODY="$(clean_text "Attached: $NAME")"
ATTACH_URL="$(fileurl "$COPY")"

DESKTOP_ID="$(xdg-mime query default x-scheme-handler/mailto 2>/dev/null | head -n 1)"
DESKTOP_FILE="$(find_desktop "$DESKTOP_ID" 2>/dev/null || true)"
EXEC=()
[ -n "$DESKTOP_FILE" ] && read_exec "$DESKTOP_FILE"
WHO="$(printf '%s %s' "$DESKTOP_ID" "$(basename -- "${EXEC[0]:-}")" | tr '[:upper:]' '[:lower:]')"
log "mail $FILE via '${DESKTOP_ID:-none}' (${DESKTOP_FILE:-no desktop file}: ${EXEC[*]:-})"

thunderbird_compose() {
  [ "${#EXEC[@]}" -gt 0 ] || EXEC=(thunderbird)
  run "${EXEC[@]}" -compose "subject='$SUBJECT',body='$BODY',attachment='$ATTACH_URL'"
  ack "ok attached thunderbird"
}
# the mail client xdg-email itself would start (GNOME: gio's default, KDE: emaildefaults)
xdg_email_client() {
  local c="" profile k
  if command -v gio >/dev/null 2>&1; then
    c="$(gio mime x-scheme-handler/mailto 2>/dev/null | sed -n '1s/^.*: *//p')"
  fi
  for k in kreadconfig6 kreadconfig5; do
    command -v "$k" >/dev/null 2>&1 || continue
    profile="$("$k" --file emaildefaults --group Defaults --key Profile 2>/dev/null)"
    c="$c $("$k" --file emaildefaults --group "PROFILE_${profile:-Default}" --key EmailClient 2>/dev/null)"
    break
  done
  printf '%s' "$c" | tr '[:upper:]' '[:lower:]'
}

case "$WHO" in
  *thunderbird*|*icedove*|*betterbird*)
    thunderbird_compose
    ;;
  *kmail*)
    [ "${#EXEC[@]}" -gt 0 ] || EXEC=(kmail)
    run "${EXEC[0]}" --subject "$SUBJECT" --body "$BODY" --attach "$COPY"
    ack "ok attached kmail"
    ;;
  *claws*)
    [ "${#EXEC[@]}" -gt 0 ] || EXEC=(claws-mail)
    run "${EXEC[0]}" --compose "mailto:?subject=$(pctenc "$SUBJECT")&body=$(pctenc "$BODY")" --attach "$COPY"
    ack "ok attached claws-mail"
    ;;
  *chrome*|*chromium*|*firefox*|*brave*|*vivaldi*|*opera*|*edge*|*epiphany*|*falkon*|*librewolf*|*waterfox*|*floorp*|*zen*|*webapp*|*gmail*|*outlook*|*browser*)
    # webmail in a browser: no attachment possible -> compose + the file in the file manager
    # the file name only: the local path (user name, folders) stays out of the message
    BODY="$(clean_text "Please attach the file $NAME (shown in your file manager).")"
    run xdg-open "mailto:?subject=$(pctenc "$SUBJECT")&body=$(pctenc "$BODY")"
    reveal "$FILE"
    ack "ok webmail"
    ;;
  *)
    if [ -z "$DESKTOP_ID" ] && ! command -v xdg-email >/dev/null 2>&1; then
      reveal "$FILE"
      fail no-mail-app "no default mail application"
    fi
    # xdg-email would start Thunderbird after all (desktop-specific defaults): our own -compose
    ALT="$(xdg_email_client)"
    case "$ALT" in
      *thunderbird*|*icedove*|*betterbird*)
        EXEC=()
        for k in thunderbird betterbird icedove; do command -v "$k" >/dev/null 2>&1 && { EXEC=("$k"); break; }; done
        thunderbird_compose
        exit 0
        ;;
    esac
    # Evolution, Geary, Mailspring ... and unknown mail applications
    run xdg-email --subject "$SUBJECT" --body "$BODY" --attach "$COPY"
    ack "ok attached ${DESKTOP_ID:-xdg-email}"
    ;;
esac
exit 0
