Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Courier MTA MySQL => Alias Generator
#!/usr/bin/env ruby
# Copyright (C) 2016 Jamie, index.hm
# Released under BSD (https://opensource.org/licenses/BSD-3-Clause)
require 'mysql2'
$config = {
:file => "/etc/courier/aliases/insanity",
:description => "Insanity Radio 103.2FM Alias Table",
:copyright => "Copyright 2016 Insanity Radio",
:database => {
:host => "localhost",
:database => "mail",
:username => "alias",
:password => "alias" }}
@client = Mysql2::Client.new $config[:database]
result = @client.query("SELECT * FROM aliases WHERE expires IS NULL OR expires > NOW();")
result_map = {}
result.each do | res |
al = res["alias"] + "@" + res["domain"]
# Initialise the array for the key if it's not already
(result_map[al] ||= []) << res["target"]
end
# Join the description and copyright, then put them on a line prefixed with a comment
out = "# " + (Array($config[:description]) + Array($config[:copyright])).join("\n# ") + "\n\n"
out += "# WARNING: This file is automatically generated, and any changes will be overwritten.\n\n"
out += result_map.map { | a, t | "#{a}: #{t.join ", "}" }.join("\n")
out += "\n"
# Write the output file, then make the aliases file. Boom, done.
File.write $config[:file], out
`makealiases`
CREATE TABLE `aliases` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`domain` varchar(255) DEFAULT NULL,
`alias` varchar(255) DEFAULT NULL,
`target` varchar(255) DEFAULT NULL,
`expires` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `hm` (`domain`,`alias`,`target`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment