#!/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 axios_1 = __importDefault(require("axios"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const promises_1 = require("stream/promises");
const unzipper_1 = __importDefault(require("unzipper"));
const _1 = require(".");
const binaries = {
    darwin: {
        x64: 'go2rtc_mac_amd64.zip',
        arm64: 'go2rtc_mac_arm64.zip',
    },
    linux: {
        x64: 'go2rtc_linux_amd64',
        arm: 'go2rtc_linux_arm',
        armv6: 'go2rtc_linux_armv6',
        arm64: 'go2rtc_linux_arm64',
        i386: 'go2rtc_linux_i386',
        mipsel: 'go2rtc_linux_mipsel',
    },
    win32: {
        x64: 'go2rtc_win64.zip',
        arm64: 'go2rtc_win_arm64.zip',
        i386: 'go2rtc_win32.zip',
    },
};
const GO2RTC_VERSION = 'v1.8.5';
const arch = os_1.default.arch();
const platform = os_1.default.platform();
const filename = binaries[platform]?.[arch];
const releasesUrl = 'https://api.github.com/repos/AlexxIT/go2rtc/releases';
console.log(`Detected platform: ${platform} / ${arch}`);
const go2rtcBinaryPath = path_1.default.resolve(__dirname, '../binary');
const go2rtcFilePath = path_1.default.resolve(go2rtcBinaryPath, filename);
const go2rtcExtractedFilePath = (0, _1.go2rtcPath)();
const isZipUrl = (url) => {
    const pathArray = new URL(url).pathname.split('/');
    const fileName = pathArray[pathArray.length - 1];
    return fileName !== undefined && path_1.default.extname(fileName) === '.zip';
};
const downloadFile = async (url) => {
    console.log(`Downloading Go2Rtc ${GO2RTC_VERSION} to ${go2rtcFilePath}...`);
    const { data } = await axios_1.default.get(url, {
        onDownloadProgress: (progressEvent) => {
            if (process.env.CI || !progressEvent.total) {
                return;
            }
            const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100) + '%';
            process.stdout.write('\r' + percent);
            if (progressEvent.loaded === progressEvent.total) {
                process.stdout.write('\r');
            }
        },
        timeout: 30 * 1000, // 30s
        maxRedirects: 3,
        responseType: 'stream',
    });
    await fs_extra_1.default.ensureDir(go2rtcBinaryPath);
    const streams = [data, fs_extra_1.default.createWriteStream(go2rtcFilePath)];
    await (0, promises_1.pipeline)(streams);
    if (isZipUrl(url)) {
        console.log(`Extracting ${go2rtcFilePath} to ${go2rtcExtractedFilePath}...`);
        const directory = await unzipper_1.default.Open.file(go2rtcFilePath);
        await new Promise((resolve, reject) => {
            directory.files[0].stream().pipe(fs_extra_1.default.createWriteStream(go2rtcExtractedFilePath)).on('error', reject).on('finish', resolve);
        });
        console.log(`Removing ${go2rtcFilePath}...`);
        await fs_extra_1.default.remove(go2rtcFilePath);
    }
    else {
        console.log(`Renaming ${go2rtcFilePath} to ${go2rtcExtractedFilePath}...`);
        await fs_extra_1.default.rename(go2rtcFilePath, go2rtcExtractedFilePath);
    }
};
const getReleaseAssets = async (version) => {
    const response = await axios_1.default.get(`${releasesUrl}/tags/${version}`);
    const assets = response.data.assets.map((asset) => asset.browser_download_url);
    const files = assets.map((asset) => asset.split(`${version}/`)[1]);
    return {
        assets,
        files,
    };
};
const downloadGo2Rtc = async () => {
    const release = await getReleaseAssets(GO2RTC_VERSION);
    if (!filename || !release.assets.find((r) => r.endsWith(filename))) {
        throw new Error(`No go2rtc binary found for architecture (${platform} / ${arch})`);
    }
    const downloadUrl = release.assets.find((r) => r.endsWith(filename));
    await downloadFile(downloadUrl);
    if (platform === 'linux' || platform === 'darwin') {
        console.log(`Making ${go2rtcExtractedFilePath} executable...`);
        fs_extra_1.default.chmodSync(go2rtcExtractedFilePath, 0o755);
    }
    console.log('Done!');
};
downloadGo2Rtc();
//# sourceMappingURL=install.js.map