package leigh.gnusto;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import leigh.mecha.util.UniversalJob;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * The GnustoApp applies migrations (if needed) to load a schema into a SQL database.
 * <p>
 * Limitations: For development purposes this is currently hard-coded to load into the leigh-astro development
 * database.
 *
 * @author Alex Leigh
 */
public class GnustoApp {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(GnustoApp.class);

    public static void main(String args[]) throws PropertyVetoException, SQLException, IOException {
        // TODO: Add a switch to prepare the database
        // TODO: Make datasource configurable
        if (args.length != 1) {
            logger.info("Usage: GnustoApp sqldir");
            System.exit(UniversalJob.RET_BADARGS);
        }

        ComboPooledDataSource cpds = new ComboPooledDataSource();
        cpds.setDriverClass("com.mysql.cj.jdbc.Driver");
        cpds.setJdbcUrl("jdbc:mysql://db1.leigh-co.com/music");
        cpds.setUser("music");
        cpds.setPassword(System.getenv("MUSIC_PW"));

        Gnusto g = new Gnusto();
        Path base = Path.of(args[0]);
        try (Connection con = cpds.getConnection()) {
            con.setAutoCommit(false);
            //   g.prepare(con);
            g.migrate(con, base);
            con.commit();
        }
    }
}
