import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.commons.net.ftp.*;
import org.apache.commons.net.smtp.*;
import java.security.*;
import javax.net.ssl.*;

public class Examen2017{
    
    Scanner teclado=new Scanner(System.in);
    
    public static void main(String args[]){
        new Examen2017();
    }
    
    Examen2017(){
        try{
            // 1- Conecta con el servidor
            FTPClient cliente=conecta(); 
            // 2- Cambia al directorio examen
            cambia(cliente);
            // 3- Descarga los ficheros que hay en el directorio
            FTPFile[] ficheros=descarga(cliente);
            // 4- Modifica los datos del fichero index.html
            modifica();
            // 5-Sube los ficheros al directorio personal del alumno (Chema en mi caso)
            sube(cliente,ficheros);
            // 6-Manda un correo desde jestepa64@gmail.com QUITAR LA CONTRASEÑA
            notifica("XXX","YYY");
            // 7-Cerrando
            desconecta(cliente);
        }catch(Exception e){
            System.out.println("ERROR");
            e.printStackTrace();
        }
    }
    
    void desconecta(FTPClient cliente){
        try{
            cliente.logout();
            cliente.disconnect();
            System.out.println("7-Desconectado");
        }catch(Exception e){
            System.out.println("Error en desconecta()");
            e.printStackTrace();
        }  
    }
    
    void notifica(String a, String b){
        try{
            // Parámetros del remitente
            String server="smtp.gmail.com";
            String username=a+"@gmail.com";
            String password=b;
            int puerto=587;
            // Parametros del destinatario
            String destino="jmestepa@educa.jcyl.es";
            String asunto="Pagina web modificada por Chema";
            String mensaje="Hola. La pagina original era http://v-espino.com:3304/~dam2/examen y la modificada es http://v-espino.com:3304/~dam2/Chema";
            // Creamos un cliente SMTP seguro y nos conectamos
            AuthenticatingSMTPClient cliente=new AuthenticatingSMTPClient();
            cliente.connect(server,puerto);
            // Se establece la clave para la conexion segura
            KeyManagerFactory kmf=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(null,null);
            KeyManager km=kmf.getKeyManagers()[0];
            cliente.setKeyManager(km);
            // Enviando ehlo y starttls
            cliente.ehlo(server);
            cliente.execTLS();
            cliente.auth(AuthenticatingSMTPClient.AUTH_METHOD.PLAIN,username,password);
            // Creamos cabecera
            SimpleSMTPHeader cabecera=new SimpleSMTPHeader(username,destino,asunto);
            cliente.setSender(username);
            cliente.addRecipient(destino);
            // Enviamos DATA 
            Writer writer=cliente.sendMessageData();
            writer.write(cabecera.toString());
            writer.write(mensaje);
            writer.close();
            // Terminamos la comunicacion
            cliente.completePendingCommand();
            // Hasta luego, Lucas
            cliente.disconnect();
            System.out.println("6-Mandada la notificacion");
            
        }catch(Exception e){
            System.out.println("Error en notifica()");
            e.printStackTrace();
        }
    }
        
        
    
    void modifica(){
        try{
            FileWriter fw=new FileWriter("index2.html");
            BufferedWriter bw=new BufferedWriter(fw);
            FileReader fr=new FileReader("index.html");
            BufferedReader br=new BufferedReader(fr);
            String linea=br.readLine();
            while(linea!=null){
                if(linea.contains("MI EMPRESA")) linea=linea.replaceAll("MI EMPRESA", "CHEMA S.A.");
                if(linea.contains("<img ")) linea=linea.replaceAll("<img ", "<img width=100 eight=70 ");
                bw.write(linea);
                bw.newLine();
                linea=br.readLine();
            }
            br.close();
            fr.close();
            bw.close();
            fw.close();
            // Cambiamos index2.html por index.html borrando primero index.html
            File f1=new File("index.html");
            f1.delete();
            File f2=new File("index2.html");
            f2.renameTo(f1);
            System.out.println("4-Modificado el fichero index.html"); 
        }catch(Exception e){
            System.out.println("Error en descarga()");
            e.printStackTrace();
        }
    }
    
    FTPFile[] descarga(FTPClient cliente){
        try{
            cliente.setFileType(FTP.BINARY_FILE_TYPE);
            FTPFile[] ficheros=cliente.listFiles();
            for(int i=0;i<ficheros.length;i++){
                System.out.print("   3-Descargando: " + ficheros[i].getName() + "... ");
                FileOutputStream fos=new FileOutputStream(ficheros[i].getName());
                BufferedOutputStream bos =new BufferedOutputStream(fos);
                if (cliente.retrieveFile(ficheros[i].getName(),bos)) System.out.println("bajado fichero");
                else System.out.println("ERROR BAJANDO");
                bos.close();
                fos.close();
            }
            return ficheros;
        }catch(Exception e){
            System.out.println("Error en descarga()");
            e.printStackTrace();
            return null;
        }
    }
    
    void sube(FTPClient cliente,FTPFile[] ficheros){
        try{
            cliente.setFileType(FTP.BINARY_FILE_TYPE);
            // FTPFile[] ficheros=cliente.listFiles();
            // Ojo, estoy en public_html/examen y tengo que subir los ficheros a public_html/Chema
            cliente.changeWorkingDirectory("..");
            cliente.changeWorkingDirectory("Chema");
            for(int i=0;i<ficheros.length;i++){
                System.out.print("   5-Subiendo: " + ficheros[i].getName() + "...");
                FileInputStream fis=new FileInputStream(ficheros[i].getName());
                BufferedInputStream bis =new BufferedInputStream(fis);
                if (cliente.storeFile(ficheros[i].getName(),bis)) System.out.println("subido fichero");
                else System.out.println("ERROR SUBIENDO");
                bis.close();
                fis.close();
            }
            // Deshago el follon de los directorios
            cliente.changeWorkingDirectory("..");
            cliente.changeWorkingDirectory("examen");
        }catch(Exception e){
            System.out.println("Error en sube()");
            e.printStackTrace();
        }
    }
    
    
    void cambia(FTPClient cliente){
        try{ 
            cliente.changeWorkingDirectory("public_html");
            cliente.changeWorkingDirectory("examen");
            System.out.println("2-Cambiado al directorio examen.");
        }catch(Exception e){
            System.out.println("Error en cambia()");
            e.printStackTrace();
        }
    }
    
    FTPClient conecta(){
        String andeEstoy;
        String servFTP="";
        String usuario="dam2";
        String clave="alcachofa";
        int puerto=0;
        FTPClient cliente;
        // Pregunto donde estoy
        System.out.println("Estas en (C)asa o en el (I)nstituto ");
        andeEstoy=teclado.nextLine();
        // El servidor FTP se comporta de forma distinta desde dentro del instituto que desde fuera
        if(andeEstoy.equals("c")){
            servFTP="v-espino.com";
            puerto=3305;
        }else{
            servFTP="ftp.a31.mio";
            puerto=20;
        }
            
        try{    
            // Conectamos
            cliente=new FTPClient();
            
            if(andeEstoy.equals("c")){
                cliente.connect(servFTP,puerto);
                cliente.enterLocalPassiveMode();
            } else cliente.connect(servFTP);
            // Nos identificamos
            boolean login=cliente.login(usuario,clave);
            System.out.println("1-Conectado.");
            return cliente;
        }catch(Exception e){
            System.out.println("Error en conecta()");
            e.printStackTrace();
            return null;
        }
    }
}
            