summaryrefslogtreecommitdiff
path: root/bin/movemymail
blob: 066710433a1abd268e045b855dfaa3e96fe1c1d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env perl

use 5.032;
use strict;
use warnings;
use autodie ":all";

use Fcntl qw(LOCK_EX LOCK_NB);
use Net::Domain "hostfqdn";
use LWP::Simple qw($ua get);

# Ensure only one copy of this script is ever running, and then we assume that
# mbsync isn't already running either, as always invoked via this script.
open our $us, "<", $0 or die $!;
exit 0 unless flock $us, LOCK_EX|LOCK_NB;

our $root = "$ENV{HOME}/.fmail";

die "no movemymail\n" if -e "$ENV{HOME}/.nomovemymail";
open my $df, "-|", "df", "-kP", $root;
<$df>, my @df_fields = split " ", <$df>;
$df_fields[3] > 1048576 or die "free space low; no movemymail\n";

# See also LWP::UserAgent::is_online() and LWP::Online.
# We could check more than one website, and try each more than once, in case
# there are temporary failures.
#
# We match page content using get(), rather than just calling head(), so that
# we don't consider WiFi portal login pages to indicate connectivity.
$ua->timeout(10);
my $result = get "http://www.msftncsi.com/ncsi.txt";
unless ($result and $result eq "Microsoft NCSI") {
    grep $_ eq "--accept-offline", @ARGV
      ? exit : die "we're offline; cannot further sync mail\n"
}

system "postqueue", "-f";

# athena's 'notmuch new' cronjob is responsible for imap-dl(1) runs.  We have
# this here rather than separate cronjob entries so that hopefully mbsync adds
# its UID to the filename before nnmaildir indexes the file.
if (hostfqdn eq "athena.silentflame.com") {
    system "imap-dl", "$ENV{HOME}/.config/mailscripts/imap-dl.selene";
    system "imap-dl", "$ENV{HOME}/.config/mailscripts/imap-dl.catmail";
    system "imap-dl", "$ENV{HOME}/.config/mailscripts/imap-dl.gmail";
}

eval { system "mbsync", "purelymail" };
if (my $exception = $@) {
    local $ENV{XDG_RUNTIME_DIR} = "/run/user/$<";
    system "notify-send", "--urgency=critical", "--icon=dialog-warning",
      "'mbsync purelymail' exited nonzero";
    die $exception;
}

# Move all mail new/ -> cur/ such that notmuch never sees anything in new/.
# The reason for this is that notmuch tries to avoid moving files new/ -> cur/
# to avoid confusing Mutt, but messages in new/ aren't meant to have flags, so
# they can't be marked seen.  See id:87r1ypsb1p.fsf@tethera.net and maildir(5).
for (<$root/*/new/*>) {
    m#^\Q$root\E/([^/]+)/new/([^/]+?)(:2,[^/]*)?$# or die "inadequate glob!";
    rename $_, "$root/$1/cur/$2" . ($3 || ":2,");
}

# Useful to see if any mail has got stuck before closing laptop lid.
`mailq` =~ "Mail queue is empty" or warn "WARNING: Outbox not empty.\n";