<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information please see
 * <http://phing.info>.
 */
require_once 'phing/Task.php';
class FtpUploadTask extends Task {
    protected $filesets = array();
    private $host = null;
    private $port = 21;
    private $username = null;
    private $password = null;
    private $targetDir = '.';
    private $mode = FTP_BINARY;
    private $cleanDir = false;
    private $overwriteExisten = true;
    private $passiveMode = true;
    public function createFileSet() {
        $num = array_push($this->filesets, new FileSet());
        return $this->filesets[$num-1];
    }
    public function setOverwriteExisten($overwrite) {
        $this->overwriteExisten = (bool) $overwrite;    
    }
    public function setHost($host) {
        $this->host = $host;
    }
    public function setPassiveMode($passive) {
        $this->passiveMode = (bool)$passive;
    }
    public function setPort($port) {
        $this->port = intval($port);
    }
    
    public function setUsername($username) {
        $this->username = $username;
    }
    
    public function setPassword($password) {
        $this->password = $password;
    }
    
    public function setTargetDir($dir) {
        $this->targetDir = $dir;
    }
    
    public function setMode($mode) {
        $this->mode = (in_array(strtoupper($mode),array('TEXT','TXT','ASCII','A'))) ? FTP_ASCII : FTP_BINARY;
    }
    
    public function setCleanDir($clean) {
        $this->cleanDir = (bool)$clean;
    }
    
    public function init() {
        include_once 'Net/FTP.php';
        if (!class_exists('Net_FTP')) {
            throw new BuildException("To use FtpUpload, you must have the path to pear's Net/Ftp.php on your include_path or your \$PHP_CLASSPATH environment variable.");
        }
    }
    public function main() {
        $ftp = $this->connect();
        if($this->cleanDir) {
            $this->log('cleanup '.$this->targetDir, Project::MSG_INFO);
            $dir = str_replace('//','/',$this->targetDir.'/');
            $ftp->rm($dir, true);
            $ftp->mkdir($dir);
        }
        $res = $ftp->cd($this->targetDir);
        if(PEAR::isError($res)) {
            $this->log('try to create directory first: '.$this->targetDir, Project::MSG_WARN);
            $res = $ftp->mkdir($this->targetDir);
            if (!PEAR::isError($res)) {
                $res = $ftp->cd($this->targetDir);
                if(PEAR::isError($res)) {
                    throw new BuildException($res->getMessage());
                }
            } else {
                throw new BuildException($res->getMessage());
            }
        }
        foreach($this->filesets as $fs) {    
            $ds = $fs->getDirectoryScanner($this->project);
            $this->log('Creating directories', Project::MSG_INFO);
            $srcDirs  = $ds->getIncludedDirectories();
            foreach($srcDirs as $dirname) {
                $dirname = $this->normalizePath($dirname);
                $this->log('mkdir '.$dirname, Project::MSG_INFO);
                $res = $ftp->mkdir($dirname, true);
                if(PEAR::isError($res)) {
                    throw new BuildException($res->getMessage());
                }
            }
            
            $this->log('Uploading files', Project::MSG_INFO);
            $srcFiles = $ds->getIncludedFiles();
            $srcDir  = $fs->getDir($this->project);
            foreach($srcFiles as $to) {
                $file = new PhingFile($srcDir->getAbsolutePath(), $to);
                $from = $file->getCanonicalPath();
                $to = $this->normalizePath($to);
                $this->log('cp '.$from.' '.$to, Project::MSG_INFO);
                $res = $ftp->put($from, $to, $this->overwriteExisten, $this->mode);
                if(PEAR::isError($res)) {
                    if ($this->overwriteExisten) {
                        $this->log('Could not upload file '.$to, Project::MSG_WARN);
                        $ftp = $this->reconnect($ftp);
                        $this->log('try upload '.$from.' to '.$to.' again', Project::MSG_WARN);
                        $res = $ftp->put($from, $to, true, $this->mode);
                        if(PEAR::isError($res)) {
                            throw new BuildException($res->getMessage());
                        }
                    } else {
                        throw new BuildException($res->getMessage());
                    }
                }
            }
        }
        $ftp->disconnect();
    }
    private function connect() {
        $ftp = new Net_FTP($this->host, $this->port);
        $res = $ftp->connect();
        if(PEAR::isError($res)) {
            throw new BuildException($res->getMessage());
        }
        $res = $ftp->login($this->username, $this->password);
        if(PEAR::isError($res)) {
            throw new BuildException($res->getMessage());    
        }
        $res = ($this->passiveMode) ? $ftp->setPassive() : $ftp->setActive();
        if(PEAR::isError($res)) {
            throw new BuildException($res->getMessage());    
        }        
        return $ftp;
    }
    private function reconnect($ftp) {
        $ftp->disconnect();
        $this->log('try to reconnect', Project::MSG_WARN);
        sleep(10); // @fixme
        $ftp = $this->connect();
        return $ftp;
    }
    private function normalizePath($path) {
        return (DIRECTORY_SEPARATOR == '\\') ? str_replace('\\', '/', $path) : $path;
    }
}
?>