"use strict";
// This file is part of HFS - Copyright 2021-2023, Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CONFIG_FILE = exports.MIME_AUTO = exports.APP_PATH = exports.IS_BINARY = exports.IS_MAC = exports.IS_WINDOWS = exports.RUNNING_BETA = exports.VERSION = exports.BUILD_TIMESTAMP = exports.HFS_STARTED = exports.ORIGINAL_CWD = exports.DEV = exports.ARGS_FILE = exports.COMPATIBLE_API_VERSION = exports.API_VERSION = void 0;
const minimist_1 = __importDefault(require("minimist"));
const fs = __importStar(require("fs"));
const os_1 = require("os");
const lodash_1 = __importDefault(require("lodash"));
const path_1 = require("path");
const cross_1 = require("./cross");
const argv_1 = require("./argv");
__exportStar(require("./cross-const"), exports);
exports.API_VERSION = 13.1;
exports.COMPATIBLE_API_VERSION = 1; // the day we break with the past, we'll update this
// you can add arguments with this file, currently used for the update process on mac/linux.
// we are using homedir because it's the only stable path both the old and new process can agree on (open() doesn't preserve cwd)
exports.ARGS_FILE = (0, path_1.join)((0, os_1.homedir)(), 'hfs-args');
try {
    const s = fs.readFileSync(exports.ARGS_FILE, 'utf-8');
    console.log('Additional arguments', s);
    lodash_1.default.defaults(argv_1.argv, (0, minimist_1.default)(JSON.parse(s)));
    fs.unlinkSync(exports.ARGS_FILE);
}
catch (e) {
    if (e?.code !== 'ENOENT')
        console.error(exports.ARGS_FILE, String(e));
}
exports.DEV = process.env.DEV ? 'DEV' : '';
exports.ORIGINAL_CWD = process.cwd();
exports.HFS_STARTED = new Date();
const PKG_PATH = (0, path_1.join)(__dirname, '..', 'package.json');
exports.BUILD_TIMESTAMP = fs.statSync(PKG_PATH).mtime.toISOString();
const pkg = JSON.parse(fs.readFileSync(PKG_PATH, 'utf8'));
exports.VERSION = pkg.version;
exports.RUNNING_BETA = exports.VERSION.includes('-');
exports.IS_WINDOWS = process.platform === 'win32';
exports.IS_MAC = process.platform === 'darwin';
exports.IS_BINARY = !/node|bun/.test((0, path_1.basename)(process.execPath)); // this won't be node if pkg was used
exports.APP_PATH = (0, path_1.dirname)(exports.IS_BINARY ? process.execPath : __dirname); // __dirname's parent can be compared with cwd
exports.MIME_AUTO = 'auto';
exports.CONFIG_FILE = 'config.yaml';
if (argv_1.argv.version) {
    process.stdout.write(exports.VERSION + '\n');
    process.exit(0);
}
// we want this to be the first stuff to be printed, then we print it in this module, that is executed at the beginning
if (exports.DEV) {
    console.clear();
    process.env.DEBUG = 'acme-client';
}
console.log(`HFS ~ HTTP File Server`);
console.log(`© Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt`);
console.log('Started', (0, cross_1.formatTimestamp)(exports.HFS_STARTED), exports.DEV);
console.log('Version', exports.VERSION || '-');
console.log('Build', exports.BUILD_TIMESTAMP || '-');
// still considering whether to use ".hfs" with Windows users, who may be less accustomed to it
const dir = argv_1.argv.cwd || useHomeDir() && (0, path_1.join)((0, os_1.homedir)(), '.hfs');
if (dir) {
    try {
        fs.mkdirSync(dir, { recursive: true });
    }
    catch (e) {
        if (e.code !== 'EEXIST')
            console.error(e);
    }
    process.chdir(dir);
}
else if (process.cwd().startsWith(process.env.windir + '\\')) // this happens if you run hfs from task scheduler
    process.chdir(exports.APP_PATH);
console.log('Working directory (cwd)', process.cwd());
if (exports.APP_PATH !== process.cwd())
    console.log('App', exports.APP_PATH);
console.log('Node', process.version);
const bun = globalThis.Bun;
if (bun)
    console.log('Bun', bun.version);
console.log('Platform', process.platform, process.arch, exports.IS_BINARY ? 'binary' : (0, path_1.basename)(process.execPath));
console.log('Pid', process.pid);
setImmediate(() => // after commands.ts has handled console.debug
 console.debug("Args", argv_1.argv));
function useHomeDir() {
    if (!exports.IS_WINDOWS || !exports.IS_BINARY)
        return true;
    try {
        fs.accessSync(exports.CONFIG_FILE, fs.constants.W_OK);
    }
    catch (e) {
        if (e.code !== 'ENOENT')
            return true;
        try {
            fs.writeFileSync(exports.CONFIG_FILE, ''); // not found, try to create
            fs.unlinkSync(exports.CONFIG_FILE);
        }
        catch {
            return true;
        }
    }
}
