/*
 * Copyright 
 *   2008 axYus - www.axyus.com
 *   2008 Christophe Marchand
 * 
 * This file is part of XEMELIOS.
 * 
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.cp.buildtools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import jonelo.jacksum.algorithm.AbstractChecksum;
import jonelo.jacksum.algorithm.MD;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 *
 * @author chm
 */
public class UploadChecker {
    private String url,tmpDir;
    private File fTmpDir;
    
    public UploadChecker(String urlToCheck, String tmpDir) {
        super();
        this.url=urlToCheck;
        if(!url.startsWith("http://")) {
            url = "file://"+System.getProperty("user.dir")+"/"+url;
        }
        this.tmpDir = tmpDir;
        fTmpDir = new File(tmpDir);
    }
    public void run() throws Exception  {
        StringBuffer errors = new StringBuffer();
        URL updateFileUrl = new URL(url);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputStream is = null;
        Document updateStruct = db.parse(is = updateFileUrl.openStream());
        is.close();
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xp = xpf.newXPath();
        NodeList nl = (NodeList)xp.evaluate("//files", updateStruct,XPathConstants.NODESET);
        for(int i=0;i<nl.getLength();i++) {
            Element files = (Element)nl.item(i);
            String root = files.getAttribute("root");
            NodeList nlf = (NodeList)xp.evaluate("./file", files, XPathConstants.NODESET);
            for(int j=0;j<nlf.getLength();j++) {
                Element file = (Element)nlf.item(j);
                String name= file.getAttribute("name");
                String location = file.getAttribute("source");
                String md5 = file.getAttribute("md5");
                errors.append(downloadFile(root+"/"+location,name,md5));
            }
        }
        if(errors.length()>0) {
            throw new Exception(errors.toString());
        }
    }
    
    protected String downloadFile(String urlToDownload, String fileName, String md5) throws Exception {
        URL url = new URL(urlToDownload);
        AbstractChecksum checksum = new MD("MD5");
        FileOutputStream fos;
        File tmpFile = new File(fTmpDir,fileName);
        fos = new FileOutputStream(tmpFile);
        InputStream is = url.openStream();
        byte[] buffer = new byte[1024];
        int read = is.read(buffer);
        while (read > 0) {
            fos.write(buffer, 0, read);
            checksum.update(buffer, 0, read);
            read = is.read(buffer);
        }
        is.close();
        fos.flush();
        fos.close();
        if (!md5.equals(checksum.getFormattedValue())) {
            return fileName+" has invalid signature: "+checksum.getFormattedValue()+" - expected: "+md5+"\n";
        } else {
            tmpFile.delete();
        }
        return "";
    }
    
    public static void main(String[] args) {
        if(args.length>0) {
            try {
                new UploadChecker(args[0], args[1]).run();
            } catch(Exception ex) {
                System.err.println(ex.getMessage());
                System.exit(2);
            }
        } else {
            displaySyntax();
            System.exit(1);
        }
        System.exit(0);
    }
    
    protected static void displaySyntax() {
        System.out.println(UploadChecker.class.getName()+" <urlToCheck> <tmpDir>");
    }

}
