package com.yfd.platform.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class MySQLBackupRestore {

    private final String host;
    private final String port;
    private final String user;
    private final String password;
    private final String database;

    public MySQLBackupRestore(String host, String port, String user, String password, String database) {
        this.host = host;
        this.port = port;
        this.user = user;
        this.password = password;
        this.database = database;
    }

    public void backup(String backupFile) throws IOException, InterruptedException {
        String cmd = String.format("mysqldump -h%s -P%s -u%s -p%s %s > %s",
                host, port, user, password, database, backupFile);

        Process process = Runtime.getRuntime().exec(new String[]{"bash", "-c", cmd});
        int processComplete = process.waitFor();

        if (processComplete == 0) {
            log.info("Backup completed successfully.");
        } else {
            log.info("Backup failed.");
        }
    }

    public void restore(String backupFile) throws IOException, InterruptedException {
        String[] executeCmd = new String[]{"mysql", database, "-u" + user, "-p" + password, "-e", "source " + backupFile};

        Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
        int processComplete = runtimeProcess.waitFor();

        if (processComplete == 0) {
            log.info("Database restored successfully");
        } else {
            log.error("Could not restore the database");
        }
    }

    public static void main(String[] args) {
        MySQLBackupRestore backupRestore = new MySQLBackupRestore("localhost", "3306", "root", "123456", "of_cd1");

        try {
            backupRestore.backup("backup.sql");
            //backupRestore.restore("D:/backup.sql");
        } catch (IOException | InterruptedException e) {
            log.error(e.getMessage());;
        }
    }
}
