octavian-nita
8/6/2014 - 9:36 AM

Back up a directory to your email (+ nice utility to detect the code base of a class)

Back up a directory to your email (+ nice utility to detect the code base of a class)

#!/usr/bin/env groovy

import javax.activation.*
import javax.mail.*
import javax.mail.internet.*

@Grapes ([
    @Grab (group = 'javax.activation', module = 'activation', version = '1.1.1'),
    @Grab (group = 'javax.mail', module = 'mail', version = '1.4.5')
])

def dirToBackup = location(getClass()).absolutePath
def archiveName = dirToBackup + '.zip'

def host = 'smtp.googlemail.com'
def port = '465'
def user = 'octavian.nita@gmail.com'
def pass = '*****'

def props = new Properties() ;
props.put('mail.smtp.host', host)
props.put('mail.smtp.user', user)
props.put('mail.smtp.port', port)
props.put('mail.smtp.auth', 'true')
props.put('mail.smtp.starttls.enable','true')

def transport = null
try {
    def ant = new AntBuilder()

    // Delete the archive:
    ant.delete(file: archiveName)

    // Archive the directory to backup:
    ant.zip(destfile: archiveName, basedir: dirToBackup, excludes: '**/*.bat')

    // Email (using Google) the newly created archive:
    def session = Session.getInstance(props, null)
    def message = new MimeMessage(session)

    message.subject = '[bkp] ' + location(getClass()).absolutePath
    message.from = new InternetAddress(user)
    message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(user))

    multipart = new MimeMultipart()

    messageBodyPart = new MimeBodyPart()
    messageBodyPart.text = 'Backup for ' + archiveName
    multipart.addBodyPart(messageBodyPart)

    messageBodyPart = new MimeBodyPart()
    messageBodyPart.dataHandler = new DataHandler(new FileDataSource(archiveName))
    messageBodyPart.fileName = 'attachment.zip'
    multipart.addBodyPart(messageBodyPart)

    message.content = multipart

    transport = session.getTransport('smtps');

    println('      [***] Connecting to Gmail...')
    transport.connect(host, port.toInteger(), user, pass)

    println('      [***] Sending message...')
    transport.sendMessage(message, message.allRecipients)
    println('      [***] Message sent!')
} catch (e) {
    e.printStackTrace()
} finally {
    if (transport != null) {
        println('      [***] Closing Gmail connection...')
        try {
            transport.close()
        } catch (e) {
            e.printStackTrace()
        }
    }
}
println('      [***] Done.')

// --- Helpers

private File location(Class<?> clazz = getClass()) {
    if (!clazz) {
        return null
    }

    String codeBase = clazz.protectionDomain?.codeSource?.location?.path
    if (!codeBase) {
        def classRelativePath = clazz.name.replace('.', '/') + '.class'
        def classUrl = clazz.classLoader?.getResource(classRelativePath)

        if (!classUrl) {
            classRelativePath = clazz.name.replace('.', '/') + '.groovy'
            classUrl = clazz.classLoader?.getResource(classRelativePath)
            if (!classUrl) {
                return null
            }
        }

        codeBase = classUrl as String
        if ('jar'.equalsIgnoreCase(classUrl.protocol)) {
            codeBase = codeBase.substring(4).replace('!/' + classRelativePath, '')
        } else {
            codeBase = codeBase.replace(classRelativePath, '')
        }
    }

    if (codeBase.startsWith('file:')) {
        codeBase = codeBase.substring(5)
    }

    def final location = new File(codeBase)
    location.exists() ? (location.isFile() ? location.parentFile.absoluteFile : location.absoluteFile) : null
}