/* desc: This script uploaed all files in a directory (exception can be specified) to a ftp server. 
 * copyright (c) 2014 netmodule ag, switzerland
 */


template uploader {   
    workfile="current.csv";
    path="";
    removefilesafterupload=false;
    server="";
    serverpath="/";
    user="";
    password="";

    void uploader(string path) {
        dh=opendir(path);    
        if(dh == -1) {
           nb_syslog("path %s not existent, exiting",path);     
           exit(1);           
        } else {
            nb_syslog("uploader path: %s", path);
            closedir(dh);
        }
        this.path = path;
    }

    int uploadfiles() {
        nb_syslog("starting uploading");
        files=mkarray();
        handle = opendir(this.path);
        if (handle != -1) {
            while ((entry = readdir(handle))) {
                if (entry == ".") continue;
                if (entry == "..") continue;
                if (entry == this.workfile) continue;
                files=array_merge(files,entry);
            }
            closedir(handle);
        } else {
            nb_syslog("cannot open directory %s", this.path);
        }
        // sort old to new
        qsort(files);
        // get current filesizes
        dump(files);
        for(i=0;i<length(files);i++){
            // lets upload every file
            if (nb_transfer_put(this.user, this.password, sprintf("%s/%s/%s", this.server, this.serverpath,files[i]), sprintf("%s%s",this.path,files[i])) == 0) {
                nb_syslog("stored '%s%s' on remote site", this.path, files[i]);
                if(this.removefilesafterupload) {
                    if(remove(sprintf("%s%s",this.path,files[i]))) {
                        nb_syslog("file %s%s removed after upload", this.path, files[i]);
                    } else {
                        nb_syslog("file %s%s can't be removed after upload", this.path, files[i]);
                    }
                }
            } else {
                nb_syslog("upload of '%s%s' was not successfull ", this.path, files[i]);
            }
        }
    return 0;
    }
} // of template uploader


########### The real program ###############

u = new uploader("/logger/");
u.server="ftp://ftp.srl.cl/";
u.serverpath="/buslogger/";
u.user="ftpsrl";
u.password="gW&lkdDm^d[y";
u.removefilesafterupload=true;
u.uploadfiles();
