Move the "mv" invalid destination user check into the runner.
[mailshears.git] / lib / mv / plugins / postfixadmin.rb
1 require 'pg'
2
3 require 'common/postfixadmin_plugin'
4 require 'mv/mv_plugin'
5
6 class PostfixadminMv
7
8 include PostfixadminPlugin
9 include MvPlugin
10
11 def mv_user(user_from, user_to)
12 if not user_exists(user_from)
13 raise NonexistentUserError.new("source user #{user_from} does not exist")
14 end
15
16 user_to_parts = user_to.split('@')
17 localpart_to = user_to_parts[0]
18 domain_to = user_to_parts[1]
19
20 if not domain_exists(domain_to)
21 msg = "destination domain #{domain_to} does not exist"
22 raise NonexistentDomainError.new(msg)
23 end
24
25 mailbox_query = 'UPDATE mailbox SET '
26 mailbox_query += ' username=$1,'
27 mailbox_query += ' domain=$2,'
28 mailbox_query += " maildir=CONCAT($2, '/', $3, '/'),"
29 mailbox_query += ' local_part=$3 '
30 mailbox_query += 'WHERE username=$4;'
31
32 alias_query1 = 'UPDATE alias SET '
33 alias_query1 += ' address=$1,'
34 alias_query1 += ' domain=$2,'
35 alias_query1 += ' goto=REPLACE(goto, $4, $1) '
36 alias_query1 += 'WHERE address=$4;'
37
38 alias_query2 = 'UPDATE alias SET '
39 alias_query2 += 'goto=REPLACE(goto, $4, $1);'
40
41 sql_queries = [mailbox_query, alias_query1, alias_query2]
42
43 begin
44 connection = PGconn.connect(@db_host,
45 @db_port,
46 @db_opts,
47 @db_tty,
48 @db_name,
49 @db_user,
50 @db_pass)
51
52 sql_queries.each do |sql_query|
53 varchar = 1043 # from pg_type.h
54 params = [{:value => user_to, :type => varchar},
55 {:value => domain_to, :type => varchar},
56 {:value => localpart_to, :type => varchar},
57 {:value => user_from, :type => varchar}]
58 connection.query(sql_query, params)
59 end
60
61 connection.close()
62
63 rescue PGError => e
64 # Pretend like we're database-agnostic in case we ever are.
65 raise DatabaseError.new(e)
66 end
67 end
68
69
70 end