]> gitweb.michael.orlitzky.com - mailshears.git/blob - bin/mailshears
Prettied up the output with a header.
[mailshears.git] / bin / mailshears
1 #!/usr/bin/ruby -wKU
2 #
3 # mailshears, to prune unused mail directories.
4 #
5 # Mail accounts for virtual hosts are stored in SQL, and managed by
6 # Postfixadmin. However, the physical directories are handled by
7 # Postfix/Dovecot and are left untouched by Postfixadmin. This is good
8 # for security, but comes at a cost: Postfixadmin can't remove a
9 # user's mail directory when his or her account is deleted.
10 #
11 # This program compares the list of filesystem accounts with the ones
12 # in the database. It outputs any accounts that exist in the
13 # filesystem, but not the database.
14 #
15
16 # We need Pathname to get the real filesystem path
17 # of this script (and not, for example, the path of
18 # a symlink which points to it.
19 require 'pathname'
20
21 # This bit of magic adds the parent directory (the
22 # project root) to the list of ruby load paths.
23 # Thus, our require statements will work regardless of
24 # how or from where the script was run.
25 executable = Pathname.new(__FILE__).realpath.to_s
26 $: << File.dirname(executable) + '/../'
27
28 # Load our config file.
29 require 'bin/configuration'
30
31 # And the necessary classes.
32 require 'src/errors.rb'
33 require 'src/exit_codes.rb'
34 require 'src/dovecot_mailstore'
35 require 'src/postfixadmin_db'
36
37 dms = DovecotMailstore.new(Configuration::MAIL_ROOT)
38
39 pgadb = PostfixadminDb.new(Configuration::DBHOST,
40 Configuration::DBPORT,
41 Configuration::DBOPTS,
42 Configuration::DBTTY,
43 Configuration::DBNAME,
44 Configuration::DBUSER,
45 Configuration::DBPASS)
46
47 begin
48 # Get the list of accounts according to the filesystem.
49 fs_accts = dms.get_accounts_from_filesystem()
50 rescue StandardError => e
51 puts "There was an error retrieving accounts from the filesystem: #{e.to_s}"
52 Kernel.exit(ExitCodes::FILESYSTEM_ERROR)
53 end
54
55 begin
56 # ...and according to the Postfixadmin database.
57 db_accts = pgadb.get_accounts_from_db()
58 rescue DatabaseError => e
59 puts "There was an error connecting to the database: #{e.to_s}"
60 Kernel.exit(ExitCodes::DATABASE_ERROR)
61 end
62
63
64 # Figure out which addresses are in the filesystem, but not in the
65 # database.
66 difference = [fs_accts - db_accts]
67
68 # Don't output any unnecessary junk. Cron might mail it to someone.
69 if difference.size > 0
70
71 # The header that we output before the list of accounts.
72 # Just the path of this script, and the current time.
73 header = "#{$0}, "
74
75 current_time = Time.now()
76 if current_time.respond_to?(:iso8601)
77 # Somehow this method is missing on some machines.
78 header += current_time.iso8601.to_s
79 else
80 # Fall back to whatever this looks like.
81 header += current_time.to_s
82 end
83
84 puts header
85 puts '-' * header.size # Underline the header.
86 puts difference
87 puts ""
88 end