#! /usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const child_process_1 = require("child_process");
const env_1 = __importDefault(require("./utils/env"));
const confFileProvidedPath = process.argv[process.argv.length - 1];
if (confFileProvidedPath === "--version" || confFileProvidedPath === "-v") {
    try {
        const packageJson = fs_1.default.readFileSync(path_1.default.resolve(__dirname, "package.json"), "utf8");
        console.log(`Turbo Sync Version: ${JSON.parse(packageJson).version}`);
    }
    catch (error) {
        console.log("Turbo Sync Version fetch failed! \nNo Worries, Turbo Sync is still installed properly");
    }
    process.exit(6);
}
console.log("Running Folder Sync ...");
const defaultConfigFilePath = path_1.default.resolve(process.cwd(), "turbosync.config.json");
const confFileComputedPath = typeof confFileProvidedPath == "string" &&
    confFileProvidedPath.endsWith(".json")
    ? path_1.default.resolve(process.cwd(), confFileProvidedPath)
    : null;
if (!fs_1.default.existsSync(defaultConfigFilePath) && !confFileComputedPath) {
    console.log("Please Provide the path to a config file or add a config file named `turbosync.config.json` to the path you're running this program");
    process.exit();
}
if (!defaultConfigFilePath &&
    confFileComputedPath &&
    !fs_1.default.existsSync(confFileComputedPath)) {
    console.log("Config File does not exist");
    process.exit();
}
try {
    const configFinalPath = fs_1.default.existsSync(defaultConfigFilePath)
        ? defaultConfigFilePath
        : confFileComputedPath && fs_1.default.existsSync(confFileComputedPath)
            ? confFileComputedPath
            : null;
    const configJSON = configFinalPath
        ? fs_1.default.readFileSync(configFinalPath, "utf8")
        : null;
    if (!configJSON)
        throw new Error("Config JSON could not be resolved. Please check your files.");
    const parsedConfigJSON = (0, env_1.default)({ json: configJSON });
    /** @type {import(".").TurboSyncConfigArray} */
    const configArray = JSON.parse(parsedConfigJSON);
    for (let i = 0; i < configArray.length; i++) {
        const config = configArray[i];
        console.log(`Syncing \`${config.title} ...\``);
        const childProcess = (0, child_process_1.spawn)("node", [
            path_1.default.resolve(__dirname, "./lib/sync.js"),
            `${JSON.stringify(config)}`,
        ], {
            stdio: "inherit",
            detached: false,
        });
    }
}
catch (error) {
    console.log(`Process Error =>`, error.message);
    process.exit();
}
setInterval(() => {
    console.log(`Turbo Sync Running for ${process.uptime().toLocaleString()}s ...`);
}, 60000);