using System.IO;
using System.Text;

namespace Noctalk_server.Server.Tor;

public static class Torrc_generator
{
    private static readonly UTF8Encoding Utf8_without_bom = new(false);

    public static void Torrc__generate__server(Tor_file_layout The_tor_file_layout, int The_local_relay_port)
    {
        Directory.CreateDirectory(The_tor_file_layout.Tor__directory);
        Directory.CreateDirectory(The_tor_file_layout.Tor__data_directory);
        Directory.CreateDirectory(The_tor_file_layout.Onion_service__directory);

        string torrc = string.Join(Environment.NewLine,
        [
            "# Noctalk_server generated torrc",
            string.Empty,
            $"DataDirectory {Torrc__quote_path(The_tor_file_layout.Tor__data_directory)}",
            string.Empty,
            "AvoidDiskWrites 1",
            "SafeLogging 1",
            "Log err stdout",
            string.Empty,
            $"GeoIPFile {Torrc__quote_path(The_tor_file_layout.Tor__geoip_path)}",
            $"GeoIPv6File {Torrc__quote_path(The_tor_file_layout.Tor__geoip6_path)}",
            string.Empty,
            $"HiddenServiceDir {Torrc__quote_path(The_tor_file_layout.Onion_service__directory)}",
            "HiddenServiceVersion 3",
            $"HiddenServicePort 65191 127.0.0.1:{The_local_relay_port}",
            string.Empty,
            "SocksPort 0",
            string.Empty
        ]);

        File.WriteAllText(The_tor_file_layout.Tor__torrc_path, torrc, Utf8_without_bom);
    }

    private static string Torrc__quote_path(string The_path)
    {
        string escapedPath = Path.GetFullPath(The_path).Replace("\\", "\\\\");
        return $"\"{escapedPath}\"";
    }
}
