<?php

$dir = dir('in');

while ($f = $dir->read()) {
    if (preg_match('/([0-9]+)\.mht\.gz$/', $f, $match)) {
        echo "$f ";
        $mhtz = file_get_contents("in/$f");
        $mht = gzdecode($mhtz);
    } else if (preg_match('/([0-9]+)\.mht$/', $f, $match)) {
        echo "$f ";
        $mht = file_get_contents("in/$f");
    } else {
        continue;
    }
    $thread = $match[1];
    if (!preg_match('/boundary="([^"]+)"/', $mht, $match)){
        echo "boundary not found\n";
        continue;
    }
    $files = explode($match[1], $mht);

    $html = explode("\r\n\r\n", $files[2]);
    $html= str_replace(['</body>','</html>'],'', base64_decode($html[1]));
	$html .= '<script type="text/javascript">const files={};';

    for ($i = 3; $i < count($files); $i++) {
        $file = explode("\r\n\r\n", $files[$i]);
        if (!preg_match('/Content-Location: ([^\r]+)/s', $file[0], $match)) {
            continue;
        }
        $filename = basename($match[1]);
        echo $filename;
        if (!preg_match('/Content-Type: ([^\r]+)/s', $file[0], $match)) {
            continue;
        }
        $mimeType = $match[1];
        $encoded = $file[1];
        
        if (preg_match('/^[0-9]+s\.[a-z]{3,4}$/',$filename)) {
            $html= str_replace("src=\"$filename\"","src=\"data:$mimeType;base64,$encoded\"", $html);
            $html= str_replace("src=$filename","src=\"data:$mimeType;base64,$encoded\"", $html);
            $html= str_replace("src='$filename'","src=\"data:$mimeType;base64,$encoded\"", $html);
        } else {
			$html .= "files[\"$filename\"] = {mime:\"$mimeType\",data:\"" . $encoded. "\"};";
        }
    }

    $html .= 'const link = document.getElementsByTagName("a");
        function base64ToBlob(base64, mime) {
            const bin = atob(base64);
            const len = bin.length;
            const u8arr = new Uint8Array(len);
            for (let i = 0; i < len; i++) {
                u8arr[i] = bin.charCodeAt(i);
            }
            return new Blob([u8arr], { type: mime });
        }
        for(let i=0; link[i]; i++){
            const href = link[i].getAttribute("href");
            if (files[href]) {
                const blob = base64ToBlob(files[href].data, files[href].mime);
                link[i].href = URL.createObjectURL(blob);
            }
        }
    </script></body></html>';

    file_put_contents("out/$thread.html", $html);

    echo "ok \n";
}