
project.Scp = Scp.class
project.SshExec = SshExec.class

configurations {
    sshAntTask
}

dependencies {
    sshAntTask "org.apache.ant:ant-jsch:1.8.2"
}

tasks.withType(SshTask) {
    sshAntClasspath = configurations.sshAntTask
}

abstract class SshTask extends DefaultTask {
    @InputFiles
    FileCollection sshAntClasspath

    @Input
    String host

    @Input
    String userName

    @Input
    String password

    @TaskAction
    def executeActions() {
        ant.taskdef(name: 'scp',
                classname: 'org.apache.tools.ant.taskdefs.optional.ssh.Scp',
                classpath: sshAntClasspath.asPath,
                loaderref: 'ssh')
        ant.taskdef(name: 'sshexec',
                classname: 'org.apache.tools.ant.taskdefs.optional.ssh.SSHExec',
                classpath: sshAntClasspath.asPath,
                loaderref: 'ssh')
        doActions()
    }

    abstract void doActions()
}

class Scp extends SshTask {

    def from(Object path) {
        source << path
    }

    @InputDirectory
    File sourceDir

    @Input
    String destinationDir

    void doActions() {
        ant.sshexec(host: host, username: userName, password: password, command: "mkdir -p ${destinationDir}")
        ant.scp(remotetodir: "${userName}@${host}:${destinationDir}", password: password) {
            fileset(dir: sourceDir)
        }
    }
}

class SshExec extends SshTask {
    @Input
    List<String[]> commandLines = []

    void commandLine(String... commandLine) {
        commandLines << commandLine
    }

    @Override
    void doActions() {
        commandLines.each { commandLine ->
            ant.sshexec(host: host, username: userName, password: password, command: commandLine.join(' '))
        }
    }
}