#!/bin/bash
# Wombat-Email: copies a mailbox's old mail onto this server (installed by installer/60-dovecot.sh as
# /usr/local/sbin/wombat-email-copy-mail). Usually started from the panel's Migrate page; by hand, as root:
#
#   wombat-email-copy-mail                    from another mail server, over IMAP: asks for the mailbox here,
#                                             the old server, the login and password there
#   wombat-email-copy-mail --files PATH [MAILBOX] [--into FOLDER]
#                                             from a downloaded copy: a Maildir folder (with cur/, new/,
#                                             tmp/ and .Folder ones, as shared hosting keeps it) or an mbox file;
#                                             --into keeps it apart under FOLDER (like Archive/HostGator): its
#                                             folders go inside it (FOLDER/INBOX, FOLDER/Sent...)
#   wombat-email-copy-mail --queue            the panel's requests (/var/lib/wombat-email/requests/copy/, one
#                                             JSON file per mailbox, read and deleted before copying), one after
#                                             the other; run by wombat-email-copy.path
#
# Dovecot does the copying (doveadm sync -1 over imapc, or doveadm import): folders, read marks and dates
# come along. It only ever adds: nothing on this server is deleted or changed, and nothing on the old server
# is touched. Running it again copies only what's new since the last time. Progress and results for the
# panel: /var/lib/wombat-email/copy-status.json (no passwords).
set -uo pipefail

STATUS=/var/lib/wombat-email/copy-status.json
QUEUE=/var/lib/wombat-email/requests/copy
say() { printf '\n== %s\n' "$*"; }
fail() { echo "!! $*"; exit 1; }
[ "$(id -u)" = 0 ] || fail "Run it as root."

ask() {   # VAR PROMPT [DEFAULT]
    local reply
    read -r -p "$2${3:+ [$3]}: " reply || exit 1
    printf -v "$1" '%s' "${reply:-${3:-}}"
}
mailbox_here() {   # an address that is a mailbox on this server (not an alias, not a relay account)
    local m=${1,,}
    [[ "$m" =~ ^[^@[:space:]\']+@[a-z0-9.-]+\.[a-z]{2,63}$ ]] || return 1
    [ "$(runuser -u postgres -- psql -X -At -d wombat_email -c "SELECT count(*) FROM mailboxes WHERE email = '$m' AND NOT relay" 2>/dev/null)" = 1 ]
}
# MAILBOX: its folders and how many messages each has, lined up, with thousands separated (for the email).
folders() {
    doveadm mailbox status -u "$1" messages '*' 2>/dev/null | python3 -I -c '
import sys
rows = []
for line in sys.stdin:
    name, _, n = line.rstrip().rpartition(" messages=")
    if name: rows.append((name, f"{int(n):,}"))
w = max([len(r[0]) for r in rows] + [4]); v = max([len(r[1]) for r in rows] + [1])
for name, n in rows: print(f"  {name:<{w}}  {n:>{v}}")'
}
num() { python3 -I -c 'import sys; print(f"{int(sys.argv[1] or 0):,}")' "${1:-0}"; }   # 4213 -> 4,213
js() { python3 -I -c 'import json, sys; d = json.loads(sys.stdin.read() or "{}"); [d := d.get(k, {}) if isinstance(d, dict) else {} for k in sys.argv[1:]]; print("" if d == {} else d)' "$@"; }   # JSON on stdin, KEYS...: the value
local_total() { doveadm mailbox status -u "$1" messages '*' 2>/dev/null | awk '{ sub(/messages=/, "", $NF); t += $NF } END { print t + 0 }'; }

# Logs in to the old server (HOST PORT SSLMODE LOGIN PASS in the environment) and prints one JSON line:
# {"ok": true, "prefix": "INBOX" or "", "total": messages in all folders} or {"ok": false, "why": ...}.
probe() {
    python3 -I - <<'PY'
import imaplib, json, os, re, ssl, sys
e = os.environ
def out(**k): print(json.dumps(k)); sys.exit()
try:
    ctx = ssl.create_default_context()
    if e["SSLMODE"] == "imaps":
        m = imaplib.IMAP4_SSL(e["HOST"], int(e["PORT"]), ssl_context=ctx, timeout=30)
    else:
        m = imaplib.IMAP4(e["HOST"], int(e["PORT"]), timeout=30)
        if e["SSLMODE"] == "starttls":
            m.starttls(ssl_context=ctx)
except ssl.SSLCertVerificationError:
    out(ok=False, why="cert")
except (OSError, imaplib.IMAP4.error):
    out(ok=False, why="reach")
try:
    m.login(e["LOGIN"], e["PASS"])
except imaplib.IMAP4.error:
    out(ok=False, why="login")
prefix = ""
try:
    typ, data = m.namespace()
    got = re.match(rb'\(\("([^"]*)" "(.)"', data[0] or b"")
    if got and got.group(1).upper().rstrip(b"./") == b"INBOX":
        prefix = "INBOX"
except imaplib.IMAP4.error:
    pass
total = 0
try:
    typ, rows = m.list()
    for row in rows or []:
        if not row or b"\\Noselect" in row or b"\\NonExistent" in row:
            continue
        name = re.search(rb'(?:"((?:[^"\\]|\\.)*)"|(\S+))\s*$', row)
        name = (name.group(1) or name.group(2)).decode(errors="replace") if name else None
        if not name:
            continue
        typ, st = m.status('"' + name.replace("\\", "\\\\").replace('"', '\\"') + '"', "(MESSAGES)")
        n = re.search(rb"MESSAGES (\d+)", st[0] or b"") if typ == "OK" else None
        total += int(n.group(1)) if n else 0
except imaplib.IMAP4.error:
    pass
m.logout()
out(ok=True, prefix=prefix, total=total)
PY
}
why_text() {   # WHY HOST PORT: in plain words
    case $1 in
        cert) echo "The old server's certificate isn't for $2. Use the name on its certificate: usually the provider's own server name rather than mail.yourdomain (their help pages, or your mail app's current settings, say which)." ;;
        reach) echo "Couldn't reach $2 on port $3. Check the name, and that the old account still exists." ;;
        login) echo "The old server refused the login. Check the login and password. Some providers want an \"app password\" for this, or IMAP switched on in their settings first." ;;
        *) echo "Couldn't talk to $2." ;;
    esac
}
# The panel's view of one mailbox's copy: STATE plus key=value fields, merged into copy-status.json.
status() {   # MAILBOX STATE [key=value...]
    local mb=$1 st=$2; shift 2
    python3 -I - "$STATUS" "$mb" "$st" "$@" <<'PY'
import fcntl, json, os, sys, time
path, mb, st, pairs = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4:]
with open(path + ".lock", "w") as lk:
    fcntl.flock(lk, fcntl.LOCK_EX)
    try: all_ = json.load(open(path))
    except Exception: all_ = {}
    s = all_.get(mb, {}) if st != "running" or all_.get(mb, {}).get("state") == "running" else {k: v for k, v in all_.get(mb, {}).items() if k in ("host", "port", "login", "copies")}
    s["state"] = st
    for p in pairs:
        k, _, v = p.partition("=")
        s[k] = int(v) if v.lstrip("-").isdigit() else v
    s["updated"] = int(time.time())
    if st == "running" and "started" not in s: s["started"] = int(time.time())
    if st in ("ok", "failed"): s["finished"] = int(time.time())
    if st == "ok": s["copies"] = s.get("copies", 0) + 1
    all_[mb] = s
    json.dump(all_, open(path + ".new", "w"), indent=1); os.chmod(path + ".new", 0o644); os.replace(path + ".new", path)
PY
}
. /usr/local/lib/wombat-email/common.sh   # tell_owner

# Copies MBOX from HOST:PORT (LOGIN, PASS); progress to the status file when PANEL=1, else to the screen.
copy_imap() {   # MBOX HOST PORT LOGIN  (PASS in the environment)
    local mbox=$1 host=$2 port=$3 login=$4 ssl=imaps p before total prefix out conf= rc pid now done
    [ "$port" = 143 ] && ssl=starttls
    [ "${PANEL:-0}" = 1 ] && status "$mbox" running "host=$host" "port=$port" "login=$login" "step=Logging in to $host" done=0 total=0
    p=$(HOST=$host PORT=$port SSLMODE=$ssl LOGIN=$login probe)
    if [ "$(js ok <<<"$p")" != True ]; then
        local why; why=$(why_text "$(js why <<<"$p")" "$host" "$port")
        [ "${PANEL:-0}" = 1 ] && status "$mbox" failed "message=$why" step=
        echo "!! $why"; return 1
    fi
    prefix=$(js prefix <<<"$p"); total=$(js total <<<"$p")
    before=$(local_total "$mbox")
    [ "${PANEL:-0}" = 1 ] && status "$mbox" running "step=Copying" done=0 "total=$total"
    out=$(mktemp) pid=
    # Ctrl+C or a stop: the copy in the background stops too (it ignores Ctrl+C itself) and no file is left behind.
    trap 'trap - INT TERM; [ -n "$pid" ] && kill "$pid" 2>/dev/null; rm -f ${conf:+"$conf"} "$out"; exit 130' INT TERM
    # The password goes to Dovecot in a root-only file (the server's own config plus that one line), never on a
    # command line, where anyone on the server could see it.
    conf=$(umask 077; mktemp /run/wombat-email-copy.XXXXXX.conf)
    { grep -m1 '^dovecot_config_version' /etc/dovecot/dovecot.conf; echo '!include /etc/dovecot/dovecot.conf'
      printf 'imapc_password = "%s"\n' "$(printf %s "$PASS" | sed 's/[\\"]/\\&/g')"; } > "$conf"
    doveadm -c "$conf" -o "imapc_host=$host" -o "imapc_port=$port" -o "imapc_ssl=$ssl" -o "imapc_user=$login" \
        -o ssl_client_ca_dir=/etc/ssl/certs ${prefix:+-o imapc_list_prefix=$prefix} sync -1 -R -u "$mbox" imapc: > "$out" 2>&1 &
    pid=$!
    while kill -0 "$pid" 2>/dev/null; do
        sleep 3
        now=$(local_total "$mbox"); done=$(( now - before )); [ "$done" -ge 0 ] || done=0
        [ "${PANEL:-0}" = 1 ] && status "$mbox" running "step=Copying" "done=$done" "total=$total"
    done
    wait "$pid"; rc=$?
    rm -f "$conf"                     # the password's file: gone as soon as the copy ends
    trap - INT TERM
    grep -v 'Info: imapc' "$out" | sed 's/^/   /'
    rm -f "$out"
    now=$(local_total "$mbox"); done=$(( now - before )); [ "$done" -ge 0 ] || done=0
    if [ $rc -ne 0 ]; then
        [ "${PANEL:-0}" = 1 ] && status "$mbox" failed "message=The copy stopped partway (the server's log has why). Copy again carries on where it stopped." "done=$done" step=
        return 1
    fi
    [ "${PANEL:-0}" = 1 ] && status "$mbox" ok "done=$done" "total=$total" "now=$now" step= message=
    return 0
}

# ---- the panel's queue
if [ "${1:-}" = --queue ]; then
    exec 9>/run/wombat-email-copy.lock
    flock -n 9 || exit 0          # one at a time; the one running picks up requests made meanwhile
    while :; do
        req=$(ls -tr "$QUEUE"/*.json 2>/dev/null | head -1)
        [ -n "$req" ] || break
        # Read it, then delete it at once: the password lives only in this process from here on.
        vals=$(python3 -I -c 'import json, sys; d = json.load(open(sys.argv[1])); print("\t".join(str(d.get(k, "")).replace("\t", " ") for k in ("mailbox", "host", "port", "login", "password")))' "$req" 2>/dev/null)
        rm -f "$req"
        IFS=$'\t' read -r mbox host port login PASS <<<"$vals"
        export PASS
        if ! mailbox_here "$mbox" || ! [[ "$host" =~ ^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || ! [[ "$port" =~ ^[0-9]+$ ]]; then
            unset PASS; continue
        fi
        mbox=${mbox,,}
        if PANEL=1 copy_imap "$mbox" "$host" "$port" "$login" > /dev/null; then
            unset PASS
            new=$(js "$mbox" done < "$STATUS") all=$(js "$mbox" total < "$STATUS")
            if [ "${new:-0}" = 0 ]; then fresh="Nothing new since the last copy."
            elif [ "$new" = "$all" ]; then fresh=""
            else fresh="$(num "$new") of them new this time."; fi
            tell_owner "old mail copied into $mbox" "$mbox has its old mail from $host: $(num "$all") messages.${fresh:+
$fresh}

$(folders "$mbox")

Next: switch the domain's mail here (Domains),
then press Copy again on Migrate a day later.
Nothing at the old provider was touched."
        else
            unset PASS
            tell_owner "copying old mail into $mbox stopped" "Copying $mbox's old mail from $host stopped:
$(js "$mbox" message < "$STATUS")

Nothing was deleted, here or there.
Fix that, then press Copy again on Migrate: it carries on."
        fi
    done
    exit 0
fi

# ---- from a downloaded copy
if [ "${1:-}" = --files ]; then
    into=
    args=()
    shift
    while [ $# -gt 0 ]; do
        case $1 in
            --into) [ $# -ge 2 ] || fail "--into needs a folder, like Archive/HostGator"; into=$2; shift 2 ;;
            *) args+=("$1"); shift ;;
        esac
    done
    set -- --files "${args[@]}"
    src=${2:-}
    [ -n "$src" ] && [ -e "$src" ] || fail "Give the downloaded folder or file: wombat-email-copy-mail --files PATH [MAILBOX]"
    if [ -d "$src" ]; then
        [ -d "$src/cur" ] || [ -d "$src/new" ] || ls -d "$src"/.[!.]*/cur > /dev/null 2>&1 \
            || fail "$src isn't a Maildir: one has cur/ and new/ folders (and .Sent and the like). Point at the folder for one mailbox."
        kind=maildir
    else
        head -c 5 "$src" | grep -q '^From ' || fail "$src isn't an mbox file (those start with \"From \")."
        kind=mbox
    fi
    mbox=${3:-}
    [ -n "$mbox" ] || ask mbox "Which mailbox on this server gets it (like you@example.com)"
    mailbox_here "$mbox" || fail "$mbox isn't a mailbox on this server. Add it in the panel first (Mailboxes)."
    mbox=${mbox,,}
    # Dovecot reads it as the mail user: a private copy it can read, removed afterwards.
    work=$(mktemp -d /var/tmp/wombat-email-import.XXXXXX)
    trap 'rm -rf "$work"' EXIT
    cp -a "$src" "$work/mail"
    # Some hosts keep mail compressed (cPanel's Dovecot: gzip; others bzip2, xz or zstd), each file whole
    # inside. Dovecot here reads plain mail, so each compressed message is unpacked in this private copy.
    unpacked=0
    while IFS= read -r -d '' f; do
        case $(head -c 4 "$f" | od -An -tx1 | tr -d ' \n') in
            1f8b*) dec=(gzip -dc) ;;
            425a68*) dec=(bzip2 -dc) ;;
            fd377a58*) dec=(xz -dc) ;;
            28b52ffd*) dec=(zstd -dcq) ;;
            *) continue ;;
        esac
        "${dec[@]}" "$f" > "$f.plain" && mv "$f.plain" "$f" || fail "Couldn't unpack $f (compressed, but not readable)."
        unpacked=$((unpacked + 1))
    done < <(find "$work/mail" -type f \( -path '*/cur/*' -o -path '*/new/*' \) -print0)
    [ "$unpacked" -eq 0 ] || echo "   $unpacked compressed messages unpacked (the host kept them compressed; nothing in them changes)"
    # A message's received date is its file's time, and a download or unpacking resets that (old mail then shows
    # as new). Each file gets its original time back first: the delivery time Maildir names start with
    # (1608387613.M…), else its own top Received: line, else its Date: line.
    python3 -I - "$work/mail" <<'PY'
import email.utils, glob, os, re, sys, time
def from_headers(p):
    head = b""
    with open(p, "rb") as f:
        for line in f:
            if line in (b"\n", b"\r\n"): break
            head += line
    text = re.sub(r"\r?\n[ \t]+", " ", head.decode("latin-1"))
    for name in ("received", "date"):
        for line in text.splitlines():
            if line.lower().startswith(name + ":"):
                value = line.split(";")[-1] if name == "received" else line.split(":", 1)[1]
                try: return email.utils.parsedate_to_datetime(value.strip()).timestamp()
                except (TypeError, ValueError, IndexError): return None
    return None
n = 0
files = [os.path.join(d, f) for d, _, fs in os.walk(sys.argv[1]) if os.path.basename(d) in ("cur", "new") for f in fs]   # .Sent and the like too
for p in files:
    m = re.match(r"(\d{9,10})\.", os.path.basename(p))
    t = int(m.group(1)) if m else from_headers(p)
    if t and 631152000 < t < time.time() + 86400:
        os.utime(p, (t, t)); n += 1
print(f"   {n} messages dated as they were received (not the day they were downloaded)")
PY
    chown -R vmail:vmail "$work"; chmod 700 "$work"
    parent=
    if [ -n "$into" ]; then
        # Typed with / (as mail apps show it); stored with the mailbox list's own separator
        [[ "$into" =~ ^[A-Za-z0-9\ _\&()+-]+(/[A-Za-z0-9\ _\&()+-]+)*$ ]] || fail "--into: letters, digits, spaces and / between folders, like Archive/HostGator"
        sep=$(doveadm mailbox list -u "$mbox" -s 2>/dev/null >/dev/null; doveconf -h namespace/inbox/separator 2>/dev/null); sep=${sep:-.}
        parent=${into//\//$sep}
        doveadm mailbox create -u "$mbox" -s "$parent" 2>/dev/null || true   # there already is fine
        doveadm mailbox subscribe -u "$mbox" "$parent" 2>/dev/null || true
    fi
    say "Importing into $mbox${into:+, under $into}"
    doveadm import -u "$mbox" -s "$kind:$work/mail" "$parent" all || fail "Dovecot couldn't import it (the lines above say why)."
    say "$mbox now has"
    folders "$mbox"
    echo
    echo "Done. Importing the same copy again would add it twice, so do it once per download."
    exit 0
fi
[ $# -eq 0 ] || fail "Unknown option: $1 (wombat-email-copy-mail, or wombat-email-copy-mail --files PATH [MAILBOX])"

# ---- from another mail server, over IMAP, asking at the terminal
cat <<'EOF'
Copies one mailbox's mail from your old mail server to this one: every folder, with read marks and dates.
Nothing is deleted anywhere, and you can run this again later: it then copies only what's new.
(The panel's Migrate page does the same, without a terminal.)
EOF
echo
ask mbox "The mailbox on this server (like you@example.com)"
mailbox_here "$mbox" || fail "$mbox isn't a mailbox on this server. Add it in the panel first (Mailboxes), then run this again."
mbox=${mbox,,}
ask host "The old server's IMAP name (in your mail app's settings, like imap.example.net)"
[[ "$host" =~ ^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || fail "That doesn't look like a server name."
ask port "Its port (993 almost everywhere)" 993
[[ "$port" =~ ^[0-9]+$ ]] || fail "A port is a number."
ask login "Your login there" "$mbox"
read -r -s -p "Your password there (it isn't shown or kept): " PASS || exit 1
echo
export PASS
say "Copying from $host to $mbox"
echo "   A big mailbox takes a while: about a minute per few thousand messages. It's safe to stop (Ctrl+C) and run again."
if copy_imap "$mbox" "$host" "$port" "$login"; then
    unset PASS
    say "$mbox now has"
    folders "$mbox"
    echo
    echo "Done. Run it again after your domain's mail has moved here, to bring over anything that still arrived at the"
    echo "old server meanwhile. It only adds what's new."
else
    unset PASS
    exit 1
fi
