if (dest == null || source == null) {
throw new IllegalStateException();
}
try (SftpChannel sftp = sshConfig.getSftpChannel()) {
RemoteTempFile tempFile = null;
File remoteDest = dest;
try {
if (sudo || atomic) {
if (atomicTempPath != null) {
tempFile = RemoteTempFile.create(sftp, atomicTempPath);
} else {
tempFile = RemoteTempFile.create(sftp, new RemoteFile(new File("/tmp")));
}
remoteDest = tempFile.getSshPath();
}
try (OutputStream os = sftp.writeFile(remoteDest, WriteMode.Overwrite)) {
source.copyTo(os);
}
if (chmod != null) {
sftp.chmod(remoteDest, chmod);
}
// chown and chgrp require CAP_CHOWN / root
if (chownGroup != null) {
sftp.chgrp(remoteDest, chownGroup);
}
if (chownUser != null) {
sftp.chown(remoteDest, chownUser);
}
if (tempFile != null) {
if (atomic) {
if (sudo) {
throw new UnsupportedOperationException("Atomic sudo move not yet implemented");
}
tempFile.renameTo(new RemoteFile(dest));
} else {
ShellCommand command = ShellCommand.create("/bin/cp");
command.arg(remoteDest);
command.arg(dest);
if (sudo) {
command.useSudo();
}
SshCommand sshCommand = command.withSsh(sshConfig);
sshCommand.run();
}
}
} finally {
if (tempFile != null) {
tempFile.close();
}
}
}
}