#!/usr/bin/ruby

require 'net/imap'

# Simple script to delete all emails in given IMAP inbox folder
# * Supports multiple accounts
# * Supports ssl connect (provided you have 'openssl' extension)
# * Supports quiet/verbose operation
# * Configurable 'confirm' delay
#
# Author: Wejn (wejn at box dot cz)
# License: GPL version 2.0, no latter

# accounts to flush
accts = [
    ['imap.server1.tld', 'acct1', 'pass1', :ssl],
    ['imap.server2.tld', 'acct2', 'pass2', :normal],
]

# handle verbose flags
$VERBOSE = true unless (ARGV & %w[-v --verbose]).empty?

# delay for 3 secs to give user a chance to kill it via ^C
unless (ARGV & %w'-c --confirm').empty?
    begin
        $stdout.sync = true
        print "Flushing imap(s) in: "
        3.downto(1) { |i| print "#{i}, "; sleep(1) }
        puts "0."
    rescue Interrupt
        puts "cancelled."
        exit 1
    end
end

# now for the real work
for srv, login, pass, ssl in accts
    ssl = [true, :ssl, :SSL, "ssl", "SSL"].include?(ssl)

    puts "+ Connect: #{srv} (#{ssl ? '' : '!'}ssl) / #{login} ..." if $VERBOSE

    imap = if ssl
        Net::IMAP.new(srv, 993, true)
    else
        Net::IMAP.new(srv)
    end

    imap.authenticate('LOGIN', login, pass)

    imap.select('INBOX')
    wtd = false

    imap.search(["ALL"]).each do |msg_id|
        puts "Deleting: #{msg_id} ..." if $VERBOSE
        imap.store(msg_id, "+FLAGS", [:Deleted])
        wtd = true
    end

    if wtd
        puts "+ Expunge ..." if $VERBOSE
        imap.expunge
    else
        puts "- No messages." if $VERBOSE
    end

    puts "+ Logout." if $VERBOSE
    imap.logout
    puts if $VERBOSE
end