Decompiled source of PackCheck v1.0.3

PackCheck.dll

Decompiled 2 days ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Steamworks;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("PackCheck")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.3.0")]
[assembly: AssemblyInformationalVersion("1.0.3")]
[assembly: AssemblyProduct("PackCheck")]
[assembly: AssemblyTitle("PackCheck")]
[assembly: AssemblyMetadata("AI_Assisted_Creation", "Code generated with Anthropic Claude (Claude Opus 5.5 and other Claude models, via Claude Code); designed and tested by the author")]
[assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic")]
[assembly: AssemblyVersion("1.0.3.0")]
namespace PackCheck;

public static class Api
{
	public static string[] LastJoinSummary { get; private set; } = new string[0];

	public static DateTime LastJoinTime { get; private set; }

	public static string[] DriftSummary { get; private set; } = new string[0];

	public static event Action ReportReady;

	internal static void SetJoin(string[] lines)
	{
		LastJoinSummary = lines ?? new string[0];
		LastJoinTime = DateTime.Now;
		Raise();
	}

	internal static void SetDrift(DriftReport d)
	{
		List<string> list = new List<string>();
		list.Add(d.MenuLine());
		list.AddRange(from i in (from i in d.Items
				where i.Level == Level.Mismatch
				orderby i.Prio
				select i).Take(20)
			select i.Line());
		DriftSummary = list.ToArray();
		Raise();
	}

	private static void Raise()
	{
		try
		{
			Api.ReportReady?.Invoke();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("A ReportReady listener failed: " + ex.Message));
		}
	}
}
internal class CfgEntry
{
	public string Section = "";

	public string Key = "";

	public string Value = "";

	public string Default;

	public string Type;

	public bool Orphan;

	public bool ReadOnly;

	public string Id => Section + "/" + Key;

	public bool HasDefault => Default != null;

	public bool IsDefault
	{
		get
		{
			if (Default != null)
			{
				return CfgParser.SameValue(Type, Value, Default);
			}
			return false;
		}
	}
}
internal class CfgFile
{
	public string Path = "";

	public string Kind = "bep";

	public string OwnerName;

	public string OwnerVersion;

	public string OwnerGuid;

	public List<CfgEntry> Entries = new List<CfgEntry>();

	public string Hash = "";

	private Dictionary<string, CfgEntry> _byId;

	public int KeyCount => Entries.Count;

	public CfgEntry Find(string section, string key)
	{
		if (_byId == null)
		{
			_byId = new Dictionary<string, CfgEntry>(StringComparer.OrdinalIgnoreCase);
			foreach (CfgEntry entry in Entries)
			{
				if (!_byId.ContainsKey(entry.Id))
				{
					_byId[entry.Id] = entry;
				}
			}
		}
		if (!_byId.TryGetValue(section + "/" + key, out var value))
		{
			return null;
		}
		return value;
	}
}
internal static class CfgParser
{
	internal static CfgFile Parse(string relPath, string text, Rules rules)
	{
		CfgFile cfgFile = new CfgFile
		{
			Path = relPath.Replace('\\', '/')
		};
		bool num = relPath.EndsWith(".cfg", StringComparison.OrdinalIgnoreCase);
		if (text == null)
		{
			text = "";
		}
		if (text.Length > 0 && text[0] == '\ufeff')
		{
			text = text.Substring(1);
		}
		if (num)
		{
			ParseBep(cfgFile, text);
		}
		if (!num || (cfgFile.Entries.Count == 0 && HasContent(text)))
		{
			cfgFile.Kind = "raw";
			cfgFile.Entries.Clear();
			cfgFile.Hash = RawHash(text);
			return cfgFile;
		}
		cfgFile.Hash = FileHash(cfgFile, rules);
		return cfgFile;
	}

	private static bool HasContent(string text)
	{
		string[] array = text.Split('\n');
		for (int i = 0; i < array.Length; i++)
		{
			string text2 = array[i].Trim();
			if (text2.Length > 0 && !text2.StartsWith("#"))
			{
				return true;
			}
		}
		return false;
	}

	private static void ParseBep(CfgFile file, string text)
	{
		string text2 = null;
		string text3 = null;
		string text4 = null;
		StringBuilder stringBuilder = new StringBuilder();
		string[] array = text.Split('\n');
		for (int i = 0; i < array.Length; i++)
		{
			string text5 = array[i].TrimEnd('\r', ' ', '\t').TrimStart();
			if (text5.Length == 0)
			{
				continue;
			}
			if (text5.StartsWith("##"))
			{
				string text6 = text5.Substring(2).Trim();
				if (text2 == null)
				{
					if (text6.StartsWith("Settings file was created by plugin ", StringComparison.Ordinal))
					{
						string text7 = text6.Substring("Settings file was created by plugin ".Length);
						int num = text7.LastIndexOf(" v", StringComparison.Ordinal);
						if (num > 0)
						{
							file.OwnerName = text7.Substring(0, num);
							file.OwnerVersion = text7.Substring(num + 2);
						}
						else
						{
							file.OwnerName = text7;
						}
					}
					else if (text6.StartsWith("Plugin GUID:", StringComparison.Ordinal))
					{
						file.OwnerGuid = text6.Substring("Plugin GUID:".Length).Trim();
					}
				}
				else
				{
					stringBuilder.Append(text6).Append(' ');
				}
				continue;
			}
			if (text5.StartsWith("#"))
			{
				string text8 = text5.Substring(1).TrimStart();
				if (text8.StartsWith("Setting type:", StringComparison.Ordinal))
				{
					text3 = text8.Substring("Setting type:".Length).Trim();
				}
				else if (text8.StartsWith("Default value:", StringComparison.Ordinal))
				{
					string text9 = text8.Substring("Default value:".Length);
					if (text9.StartsWith(" "))
					{
						text9 = text9.Substring(1);
					}
					text4 = Unescape(text9.Trim());
				}
				continue;
			}
			if (text5.StartsWith("[") && text5.EndsWith("]"))
			{
				text2 = text5.Substring(1, text5.Length - 2);
				text3 = null;
				text4 = null;
				stringBuilder.Length = 0;
				continue;
			}
			int num2 = text5.IndexOf(" = ", StringComparison.Ordinal);
			int num3 = 3;
			if (num2 < 0)
			{
				num2 = text5.IndexOf('=');
				num3 = 1;
			}
			if (num2 <= 0)
			{
				text3 = null;
				text4 = null;
				stringBuilder.Length = 0;
				continue;
			}
			CfgEntry item = new CfgEntry
			{
				Section = (text2 ?? ""),
				Key = text5.Substring(0, num2).Trim(),
				Value = Unescape(text5.Substring(num2 + num3).Trim()),
				Type = text3,
				Default = text4,
				Orphan = (text3 == null),
				ReadOnly = (stringBuilder.ToString().IndexOf("Read-only", StringComparison.OrdinalIgnoreCase) >= 0)
			};
			file.Entries.Add(item);
			text3 = null;
			text4 = null;
			stringBuilder.Length = 0;
		}
	}

	internal static string Unescape(string s)
	{
		if (string.IsNullOrEmpty(s) || s.IndexOf('\\') < 0)
		{
			return s ?? "";
		}
		StringBuilder stringBuilder = new StringBuilder(s.Length);
		for (int i = 0; i < s.Length; i++)
		{
			char c = s[i];
			if (c != '\\' || i + 1 >= s.Length)
			{
				stringBuilder.Append(c);
				continue;
			}
			char value;
			switch (s[i + 1])
			{
			case '\\':
				value = '\\';
				break;
			case '"':
				value = '"';
				break;
			case '\'':
				value = '\'';
				break;
			case 'n':
				value = '\n';
				break;
			case 't':
				value = '\t';
				break;
			case 'r':
				value = '\r';
				break;
			case '0':
				value = '\0';
				break;
			case 'a':
				value = '\a';
				break;
			case 'b':
				value = '\b';
				break;
			case 'f':
				value = '\f';
				break;
			case 'v':
				value = '\v';
				break;
			default:
				stringBuilder.Append(c);
				continue;
			}
			stringBuilder.Append(value);
			i++;
		}
		return stringBuilder.ToString();
	}

	internal static string Norm(string type, string value)
	{
		value = value ?? "";
		switch (type)
		{
		case "Boolean":
			return value.Trim().ToLowerInvariant();
		case "Single":
		{
			if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result2))
			{
				return result2.ToString("R", CultureInfo.InvariantCulture);
			}
			return value;
		}
		case "Decimal":
		case "Double":
		{
			if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result3))
			{
				return result3.ToString("R", CultureInfo.InvariantCulture);
			}
			return value;
		}
		case "UInt64":
		case "UInt16":
		case "UInt32":
		case "Int64":
		case "SByte":
		case "Int16":
		case "Int32":
		case "Byte":
		{
			if (long.TryParse(value.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
			{
				return result.ToString(CultureInfo.InvariantCulture);
			}
			return value;
		}
		default:
			return value;
		}
	}

	internal static bool SameValue(string type, string a, string b)
	{
		return string.Equals(Norm(type, a), Norm(type, b), StringComparison.Ordinal);
	}

	internal static bool SameValue(CfgEntry a, CfgEntry b)
	{
		if (SameValue(a.Type ?? b.Type, a.Value, b.Value))
		{
			return true;
		}
		if (b.Type != null && b.Type != a.Type)
		{
			return SameValue(b.Type, a.Value, b.Value);
		}
		return false;
	}

	internal static string FileHash(CfgFile file, Rules rules)
	{
		List<string> list = new List<string>(file.Entries.Count);
		foreach (CfgEntry entry in file.Entries)
		{
			if (rules == null || !rules.IsIgnoredKey(file.Path, entry))
			{
				list.Add(entry.Section + "\u0001" + entry.Key + "\u0001" + Norm(entry.Type, entry.Value));
			}
		}
		list.Sort(StringComparer.OrdinalIgnoreCase);
		StringBuilder stringBuilder = new StringBuilder();
		foreach (string item in list)
		{
			stringBuilder.Append(item).Append('\n');
		}
		return Hashing.Sha256Hex(stringBuilder.ToString());
	}

	internal static string RawHash(string text)
	{
		if (text.Length > 0 && text[0] == '\ufeff')
		{
			text = text.Substring(1);
		}
		StringBuilder stringBuilder = new StringBuilder(text.Length);
		string[] array = text.Split('\n');
		foreach (string text2 in array)
		{
			stringBuilder.Append(text2.TrimEnd('\r', ' ', '\t')).Append('\n');
		}
		return Hashing.Sha256Hex(stringBuilder.ToString().TrimEnd('\n'));
	}
}
internal static class Core
{
	internal static readonly HashCache Cache = new HashCache();

	internal static volatile bool InitialDone;

	internal static Dictionary<string, string> GameBlock;

	internal static List<FileRec> Dlls;

	internal static List<LoadedPlugin> Plugins;

	internal static volatile string Fingerprint = "pending";

	internal static float StartedAt;

	private static bool _pass1Queued;

	private static bool _pass2Done;

	private static DriftReport _pass1;

	internal static string MenuInfoLine;

	internal static float MenuInfoUntil;

	internal static string PendingLobbyChat;

	internal static readonly object BaselineLock = new object();

	private static bool _fpQueued;

	internal static string HashCacheFile => Path.Combine(Plugin.OutDir, "hashcache.txt");

	internal static string BaselineFile => Path.Combine(Plugin.OutDir, "baseline.txt");

	internal static void StartInitialScan()
	{
		StartedAt = Time.realtimeSinceStartup;
		ScanPaths p = Plugin.ScanPaths;
		Rules rules = Plugin.Rules;
		Worker.Enqueue("first hash pass", delegate
		{
			Stopwatch stopwatch = Stopwatch.StartNew();
			Cache.Load(HashCacheFile);
			long elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
			Cache.ResetCounters();
			Dictionary<string, string> gameBlock = Scanner.ScanGame(p, Cache, hash: true);
			long elapsedMilliseconds2 = stopwatch.ElapsedMilliseconds;
			List<FileRec> list = Scanner.ScanDlls(p, Cache, hash: true);
			long elapsedMilliseconds3 = stopwatch.ElapsedMilliseconds;
			List<FileRec> list2 = Scanner.ScanOwnFolders(p, Cache, rules, rules.OwnModFolders, hash: true);
			stopwatch.Stop();
			int hits = Cache.Hits;
			int misses = Cache.Misses;
			long bytesHashed = Cache.BytesHashed;
			try
			{
				Cache.Save(HashCacheFile);
			}
			catch (Exception ex)
			{
				Worker.Warn("Couldn't save the hash cache: " + ex.Message);
			}
			GameBlock = gameBlock;
			Dlls = list;
			InitialDone = true;
			double num = (double)bytesHashed / 1048576.0;
			double num2 = Math.Max(0.001, (double)(stopwatch.ElapsedMilliseconds - elapsedMilliseconds) / 1000.0);
			Worker.Log("Hashing done on a background thread in " + stopwatch.ElapsedMilliseconds + " ms: " + (hits + misses) + " files (" + list.Count + " DLLs, " + list2.Count + " own-mod files, game files), " + misses + " re-hashed (" + num.ToString("0.0") + " MB" + ((misses > 0) ? (", " + (num / num2).ToString("0") + " MB/s") : "") + "), " + hits + " from cache. Game " + (elapsedMilliseconds2 - elapsedMilliseconds) + " ms, DLLs " + (elapsedMilliseconds3 - elapsedMilliseconds2) + " ms, cache load " + elapsedMilliseconds + " ms.");
			Worker.ToMain(TryBuildFingerprint);
		});
	}

	internal static void SnapshotPlugins()
	{
		if (Plugins != null)
		{
			return;
		}
		List<LoadedPlugin> list = new List<LoadedPlugin>();
		foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
		{
			PluginInfo value = pluginInfo.Value;
			if (value != null && value.Metadata != null)
			{
				list.Add(new LoadedPlugin
				{
					Guid = (value.Metadata.GUID ?? pluginInfo.Key),
					Name = (value.Metadata.Name ?? ""),
					Version = ((value.Metadata.Version != null) ? value.Metadata.Version.ToString() : ""),
					Location = (value.Location ?? "")
				});
			}
		}
		Plugins = list;
		Plugin.Log.LogInfo((object)("Snapshot of " + list.Count + " loaded plugins taken."));
		TryBuildFingerprint();
	}

	internal static void TryBuildFingerprint()
	{
		if (InitialDone && Plugins != null && !_fpQueued)
		{
			_fpQueued = true;
			Func<Scanner.BuildResult> job = PrepareBuild(withConfigs: false);
			Worker.Enqueue("fingerprint", delegate
			{
				Scanner.BuildResult buildResult = job();
				Fingerprint = buildResult.Fingerprint;
				Worker.Log("Join fingerprint PC1:" + buildResult.Fingerprint + " (" + buildResult.Manifest.Plugins.Count + " plugins, " + buildResult.Manifest.Dlls.Count + " DLLs, built in " + buildResult.Ms + " ms).");
			});
		}
	}

	internal static Func<Scanner.BuildResult> PrepareBuild(bool withConfigs)
	{
		ScanPaths p = Plugin.ScanPaths;
		Rules rules = Plugin.Rules;
		List<LoadedPlugin> plugins = ((Plugins != null) ? new List<LoadedPlugin>(Plugins) : new List<LoadedPlugin>());
		Dictionary<string, string> mainGame = MainThreadGame();
		Dictionary<string, string> header = new Dictionary<string, string>
		{
			{
				"protocol",
				1.ToString()
			},
			{ "version", "1.0.3" },
			{ "profile", p.ProfileName }
		};
		return delegate
		{
			bool initialDone = InitialDone;
			Scanner.BuildResult result = Scanner.Build(p, Cache, rules, plugins, mainGame, header, initialDone, withConfigs, initialDone ? GameBlock : null, initialDone ? Dlls : null);
			if (initialDone)
			{
				try
				{
					Cache.Save(HashCacheFile);
				}
				catch
				{
				}
			}
			return result;
		};
	}

	internal static Dictionary<string, string> MainThreadGame()
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
		try
		{
			if ((Object)(object)GameNetworkManager.Instance != (Object)null)
			{
				dictionary["versionNum"] = GameNetworkManager.Instance.gameVersionNum.ToString();
			}
		}
		catch
		{
		}
		try
		{
			dictionary["unityVersion"] = Application.unityVersion;
		}
		catch
		{
		}
		try
		{
			dictionary["bepinexVersion"] = typeof(Paths).Assembly.GetName().Version.ToString();
		}
		catch
		{
		}
		try
		{
			SteamInfo(dictionary);
		}
		catch
		{
		}
		dictionary["copy"] = CopyKind();
		return dictionary;
	}

	[MethodImpl(MethodImplOptions.NoInlining)]
	private static void SteamInfo(Dictionary<string, string> g)
	{
		if (SteamClient.IsValid)
		{
			g["steamBuildId"] = SteamApps.BuildId.ToString();
			string currentBetaName = SteamApps.CurrentBetaName;
			g["steamBeta"] = (string.IsNullOrEmpty(currentBetaName) ? "public" : currentBetaName);
		}
	}

	internal static bool FrozenSet()
	{
		return !string.IsNullOrEmpty((Plugin.FrozenGamePath.Value ?? "").Trim());
	}

	internal static string CopyKind()
	{
		string text = (Plugin.ScanPaths.GameRoot ?? "").Replace('\\', '/').TrimEnd('/');
		string text2 = (Plugin.FrozenGamePath.Value ?? "").Replace('\\', '/').TrimEnd('/');
		if (text2.Length > 0 && string.Equals(text, text2, StringComparison.OrdinalIgnoreCase))
		{
			return "frozen";
		}
		if (text.IndexOf("steamapps/common", StringComparison.OrdinalIgnoreCase) >= 0)
		{
			return "steam";
		}
		return "other";
	}

	internal static void OnMainMenu()
	{
		SnapshotPlugins();
		if (!_pass1Queued)
		{
			_pass1Queued = true;
			if (Plugin.WarnIfSteamCopy.Value && FrozenSet() && CopyKind() == "steam")
			{
				ShowMenuInfo("PackCheck: running the Steam copy, not the frozen one (" + Plugin.FrozenGamePath.Value + ").");
			}
			Runner.After(3f, RunPass1);
		}
	}

	private static void RunPass1()
	{
		Func<Scanner.BuildResult> job = PrepareBuild(withConfigs: true);
		bool check = Plugin.CheckOnLaunch.Value;
		Rules rules = Plugin.Rules;
		string expGuid = Plugin.ExpectedBuildGuid.Value.Trim();
		string expAcs = Plugin.ExpectedAssemblySha256.Value.Trim();
		Worker.Enqueue("drift pass 1", delegate
		{
			Stopwatch stopwatch = Stopwatch.StartNew();
			Scanner.BuildResult res = job();
			string frozenMsg = FrozenCheck(res.Manifest, expGuid, expAcs);
			if (frozenMsg != null)
			{
				Worker.Warn(frozenMsg);
			}
			DriftReport drift = null;
			Manifest baseline = LoadBaseline();
			if (check && baseline != null)
			{
				Manifest now = WithDetails(res);
				drift = Drift.Compare(baseline, now, rules);
				if (frozenMsg != null)
				{
					drift.ExtraNotes.Add(frozenMsg);
				}
				WriteDrift(drift);
			}
			long ms = stopwatch.ElapsedMilliseconds;
			Worker.ToMain(delegate
			{
				AfterPass1(drift, frozenMsg, baseline != null, res, ms);
			});
		});
	}

	private static void AfterPass1(DriftReport drift, string frozenMsg, bool hadBaseline, Scanner.BuildResult res, long ms)
	{
		_pass1 = drift;
		int num = ((res.Configs != null) ? res.Configs.Sum((CfgFile c) => c.KeyCount) : 0);
		Plugin.Log.LogInfo((object)("Launch check (main menu): " + ((res.Configs != null) ? res.Configs.Count : 0) + " config files, " + num + " keys parsed in " + ms + " ms on the worker. " + ((drift != null) ? drift.MenuLine() : (hadBaseline ? "Drift check off." : "No baseline yet."))));
		List<string> list = new List<string>();
		if (frozenMsg != null)
		{
			list.Add(frozenMsg);
		}
		if (drift != null)
		{
			Api.SetDrift(drift);
			if (drift.NeedsPopup && Plugin.PopupOnLikelyReset.Value)
			{
				list.Add(drift.PopupText("BepInEx/PackCheck/drift-latest.txt"));
			}
			else if (drift.Items.Count > 0 || drift.ModChanges.Count > 0)
			{
				ShowMenuInfo(drift.MenuLine());
			}
			foreach (DriftItem item in drift.Items.Where((DriftItem x) => x.Level == Level.Mismatch && (x.Flag == "LIKELY RESET" || x.Flag == "FILE REGENERATED")).Take(20))
			{
				Plugin.Log.LogWarning((object)("Drift: " + item.Line()));
			}
		}
		if (list.Count > 0)
		{
			Runner.MenuPopup(string.Join("\n", list.Take(3).ToArray()));
		}
	}

	internal static void OnLobby()
	{
		if (_pass2Done)
		{
			return;
		}
		_pass2Done = true;
		SnapshotPlugins();
		Func<Scanner.BuildResult> job = PrepareBuild(withConfigs: true);
		bool check = Plugin.CheckOnLaunch.Value;
		bool auto = Plugin.AutoCreateBaseline.Value;
		Rules rules = Plugin.Rules;
		DriftReport pass1 = _pass1;
		Worker.Enqueue("drift pass 2", delegate
		{
			Scanner.BuildResult res = job();
			Manifest manifest = LoadBaseline();
			if (manifest == null)
			{
				if (auto)
				{
					SaveBaseline(res, "first run");
					Worker.ToMain(delegate
					{
						Plugin.Log.LogInfo((object)"No baseline existed: created BepInEx/PackCheck/baseline.txt from the current configs.");
						PendingLobbyChat = "No baseline yet, so I saved one from your current configs. If any were already reset, compare with the Config Changes Log first.";
					});
				}
			}
			else if (check)
			{
				DriftReport drift = Drift.Compare(manifest, WithDetails(res), rules);
				HashSet<string> before = new HashSet<string>((pass1 != null) ? pass1.Items.Select((DriftItem i) => i.Line()) : Enumerable.Empty<string>());
				List<DriftItem> fresh = drift.Items.Where((DriftItem i) => !before.Contains(i.Line())).ToList();
				WriteDrift(drift);
				Worker.ToMain(delegate
				{
					Api.SetDrift(drift);
					if (fresh.Count == 0 && pass1 != null)
					{
						Plugin.Log.LogInfo((object)"Lobby drift pass: nothing new since the main-menu pass.");
					}
					else
					{
						foreach (DriftItem item in fresh.Where((DriftItem x) => x.Level == Level.Mismatch).Take(20))
						{
							Plugin.Log.LogInfo((object)("Drift (lobby pass): " + item.Line()));
						}
						int num = fresh.Count((DriftItem i) => i.Level == Level.Mismatch && i.Flag == "LIKELY RESET");
						int num2 = fresh.Count((DriftItem i) => i.Level == Level.Mismatch);
						if (num2 > 0 || pass1 == null)
						{
							PendingLobbyChat = ((pass1 == null) ? drift.MenuLine().Replace("PackCheck: ", "") : (num2 + " more config change" + ((num2 == 1) ? "" : "s") + " since baseline (late-written configs), " + num + " look reset")) + ". See BepInEx/PackCheck/drift-latest.txt";
						}
					}
				});
			}
		});
	}

	private static Manifest WithDetails(Scanner.BuildResult res)
	{
		Manifest manifest = res.Manifest;
		manifest.Details.Clear();
		if (res.Configs != null)
		{
			foreach (CfgFile config in res.Configs)
			{
				manifest.Details[config.Path] = config;
			}
		}
		return manifest;
	}

	internal static string FrozenCheck(Manifest m, string expGuid, string expAcs)
	{
		return GameCheck.Mismatch(m, expGuid, expAcs);
	}

	internal static Manifest LoadBaseline()
	{
		lock (BaselineLock)
		{
			try
			{
				if (!File.Exists(BaselineFile))
				{
					return null;
				}
				return Manifest.Parse(File.ReadAllText(BaselineFile));
			}
			catch (Exception ex)
			{
				Worker.Warn("Couldn't read the baseline: " + ex.Message);
				return null;
			}
		}
	}

	internal static void SaveBaseline(Scanner.BuildResult res, string why)
	{
		Manifest manifest = WithDetails(res);
		manifest.Header["kind"] = "baseline";
		manifest.Header["createdUtc"] = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss", Util.Inv);
		manifest.Header["reason"] = why;
		lock (BaselineLock)
		{
			Directory.CreateDirectory(Plugin.OutDir);
			if (File.Exists(BaselineFile))
			{
				string destFileName = Path.Combine(Plugin.OutDir, "baseline-" + Util.Stamp(DateTime.Now) + ".txt");
				try
				{
					File.Copy(BaselineFile, destFileName, overwrite: true);
				}
				catch (Exception ex)
				{
					Worker.Warn("Couldn't keep the old baseline: " + ex.Message);
				}
			}
			Files.WriteAtomic(BaselineFile, manifest.Serialize(includeDetails: true));
			Files.Prune(Plugin.OutDir, "baseline-", ".txt", Plugin.KeepBaselines.Value);
		}
	}

	internal static void TakeBaseline(string why)
	{
		SnapshotPlugins();
		Func<Scanner.BuildResult> job = PrepareBuild(withConfigs: true);
		Worker.Enqueue("baseline", delegate
		{
			Scanner.BuildResult res = job();
			SaveBaseline(res, why);
			int keys = res.Configs.Sum((CfgFile c) => c.KeyCount);
			Worker.ToMain(delegate
			{
				string text = "Baseline saved: " + res.Configs.Count + " configs, " + keys + " keys, " + res.Manifest.Plugins.Count + " plugins. The previous one was kept.";
				Plugin.Log.LogInfo((object)(text + " (" + why + ")"));
				if (!Runner.Chat(text))
				{
					Runner.MenuPopup("PackCheck: " + text);
				}
			});
		});
	}

	private static void WriteDrift(DriftReport d)
	{
		try
		{
			Directory.CreateDirectory(Plugin.OutDir);
			string text = d.Text(DateTime.Now);
			File.WriteAllText(Path.Combine(Plugin.OutDir, "drift-" + Util.Stamp(DateTime.Now) + ".txt"), text);
			Files.WriteAtomic(Path.Combine(Plugin.OutDir, "drift-latest.txt"), text);
			Files.Prune(Plugin.OutDir, "drift-", ".txt", Plugin.KeepFiles.Value);
		}
		catch (Exception ex)
		{
			Worker.Warn("Couldn't write the drift report: " + ex.Message);
		}
	}

	internal static void ShowMenuInfo(string line)
	{
		MenuInfoLine = (string.IsNullOrEmpty(MenuInfoLine) ? line : (MenuInfoLine + "\n" + line));
		MenuInfoUntil = Time.realtimeSinceStartup + 20f;
	}
}
internal class DriftItem
{
	public string Flag = "";

	public int Prio;

	public Level Level;

	public string File = "";

	public string Section = "";

	public string Key = "";

	public string Baseline = "";

	public string Now = "";

	public string Default = "";

	public string Note = "";

	public string Group = "";

	public string Line()
	{
		string text = ((Section.Length > 0 || Key.Length > 0) ? ("[" + Section + "] " + Key) : "");
		return Util.Line2(File, text, Baseline + " -> " + Now, Default, Flag + ((Note.Length > 0) ? (" (" + Note + ")") : "") + ((Level == Level.Info) ? " [info]" : ""));
	}
}
internal class DriftReport
{
	public List<DriftItem> Items = new List<DriftItem>();

	public List<string> ModChanges = new List<string>();

	public List<string> GameChanges = new List<string>();

	public List<string> InfoNotes = new List<string>();

	public List<string> ExtraNotes = new List<string>();

	public string BaselineTime = "";

	public string BaselineProfile = "";

	public Dictionary<string, string> FileOwners = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

	public IEnumerable<DriftItem> Counted => Items.Where((DriftItem i) => i.Level == Level.Mismatch);

	public int Resets => Counted.Count((DriftItem i) => i.Flag == "LIKELY RESET");

	public int Regenerated => Counted.Count((DriftItem i) => i.Flag == "FILE REGENERATED");

	public int Changes => Counted.Count((DriftItem i) => i.Flag != "FILE REGENERATED");

	public bool NeedsPopup
	{
		get
		{
			if (Resets <= 0)
			{
				return Regenerated > 0;
			}
			return true;
		}
	}

	public string PopupText(string fileRel)
	{
		List<string> list = (from i in Counted
			where i.Flag == "LIKELY RESET" || i.Flag == "FILE REGENERATED"
			select i.File).Distinct<string>(StringComparer.OrdinalIgnoreCase).ToList();
		List<string> list2 = list.Select((string f) => Owner(f)).Distinct<string>(StringComparer.OrdinalIgnoreCase).ToList();
		string text = string.Join(", ", list2.Take(3).ToArray()) + ((list2.Count > 3) ? ", ..." : "");
		int resets = Resets;
		string text2 = "PackCheck: " + resets + " setting" + ((resets == 1) ? "" : "s") + " in " + list.Count + " config" + ((list.Count == 1) ? "" : "s") + " look reset to defaults (" + text + ").";
		if (Regenerated > 0)
		{
			text2 = text2 + " " + Regenerated + " file" + ((Regenerated == 1) ? " looks" : "s look") + " regenerated.";
		}
		return text2 + " Details in " + fileRel;
	}

	public string MenuLine()
	{
		return "PackCheck: " + Changes + " config change" + ((Changes == 1) ? "" : "s") + " since baseline, " + Resets + " look reset" + ((ModChanges.Count > 0) ? (", " + ModChanges.Count + " mod update" + ((ModChanges.Count == 1) ? "" : "s")) : "");
	}

	private string Owner(string file)
	{
		if (FileOwners.TryGetValue(file, out var value) && !string.IsNullOrEmpty(value))
		{
			return value;
		}
		string text = file;
		int num = text.IndexOf('/');
		if (num > 0)
		{
			return text.Substring(0, num);
		}
		if (text.EndsWith(".cfg", StringComparison.OrdinalIgnoreCase))
		{
			text = text.Substring(0, text.Length - 4);
		}
		return text;
	}

	public string Text(DateTime now)
	{
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append("PackCheck config drift, ").Append(now.ToString("yyyy-MM-dd HH:mm:ss", Util.Inv)).Append(" (local time)\n");
		stringBuilder.Append("Baseline: ").Append(BaselineTime).Append(" UTC, profile ")
			.Append(BaselineProfile)
			.Append('\n');
		stringBuilder.Append(MenuLine()).Append('\n');
		foreach (string extraNote in ExtraNotes)
		{
			stringBuilder.Append("Note: ").Append(extraNote).Append('\n');
		}
		if (GameChanges.Count > 0)
		{
			stringBuilder.Append("\n== Game changed since baseline\n");
			foreach (string gameChange in GameChanges)
			{
				stringBuilder.Append(gameChange).Append('\n');
			}
		}
		if (InfoNotes.Count > 0)
		{
			stringBuilder.Append("\n== Info\n");
			foreach (string infoNote in InfoNotes)
			{
				stringBuilder.Append(infoNote).Append('\n');
			}
		}
		if (ModChanges.Count > 0)
		{
			stringBuilder.Append("\n== Mod updates since baseline\n");
			foreach (string modChange in ModChanges)
			{
				stringBuilder.Append(modChange).Append('\n');
			}
		}
		stringBuilder.Append("\n== Config changes (file | [section] key | baseline -> now | default | flag)\n");
		if (Items.Count == 0)
		{
			stringBuilder.Append("(none)\n");
		}
		foreach (IGrouping<string, DriftItem> item in from i in Items
			group i by i.Group into g
			orderby (g.Key == "") ? 1 : 0, g.Key
			select g)
		{
			if (item.Key != "")
			{
				stringBuilder.Append("-- ").Append(item.Key).Append('\n');
			}
			else if (Items.Any((DriftItem i) => i.Group != ""))
			{
				stringBuilder.Append("-- other changes\n");
			}
			foreach (DriftItem item2 in (from i in item
				orderby i.Level, i.Prio
				select i).ThenBy<DriftItem, string>((DriftItem i) => i.File, StringComparer.OrdinalIgnoreCase).ThenBy((DriftItem i) => i.Section).ThenBy((DriftItem i) => i.Key))
			{
				stringBuilder.Append(item2.Line()).Append('\n');
			}
		}
		return stringBuilder.ToString();
	}
}
internal static class Drift
{
	internal static readonly string[] GameKeys = new string[7] { "versionNum", "buildGuid", "assemblyCSharp", "exe", "unityPlayer", "managed", "dataListing" };

	internal static DriftReport Compare(Manifest baseline, Manifest now, Rules rules)
	{
		DriftReport driftReport = new DriftReport
		{
			BaselineTime = baseline.H("createdUtc"),
			BaselineProfile = baseline.H("profile")
		};
		string[] gameKeys = GameKeys;
		foreach (string text in gameKeys)
		{
			string text2 = baseline.G(text);
			string text3 = now.G(text);
			if (!(text2 == text3) && !(text2 == "") && !(text2 == "pending") && !(text3 == "pending"))
			{
				driftReport.GameChanges.Add(text + ": " + text2 + " -> " + text3);
			}
		}
		string text4 = baseline.G("steamBuildId");
		string text5 = now.G("steamBuildId");
		if (text4 != "" && text5 != "" && text4 != text5)
		{
			driftReport.InfoNotes.Add("Steam's install has updated (build " + text4 + " -> " + text5 + ").");
		}
		Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
		string source = ((baseline.HasModsYml && now.HasModsYml) ? "yml" : "manifest");
		Dictionary<string, PackageRec> dictionary2 = baseline.PackagesFrom(source).GroupBy<PackageRec, string>((PackageRec p) => p.Name, StringComparer.OrdinalIgnoreCase).ToDictionary<IGrouping<string, PackageRec>, string, PackageRec>((IGrouping<string, PackageRec> g) => g.Key, (IGrouping<string, PackageRec> g) => g.First(), StringComparer.OrdinalIgnoreCase);
		Dictionary<string, PackageRec> dictionary3 = now.PackagesFrom(source).GroupBy<PackageRec, string>((PackageRec p) => p.Name, StringComparer.OrdinalIgnoreCase).ToDictionary<IGrouping<string, PackageRec>, string, PackageRec>((IGrouping<string, PackageRec> g) => g.Key, (IGrouping<string, PackageRec> g) => g.First(), StringComparer.OrdinalIgnoreCase);
		foreach (string item in dictionary2.Keys.Union<string>(dictionary3.Keys, StringComparer.OrdinalIgnoreCase).OrderBy<string, string>((string x) => x, StringComparer.OrdinalIgnoreCase))
		{
			dictionary2.TryGetValue(item, out var value);
			dictionary3.TryGetValue(item, out var value2);
			string text6 = (value ?? value2).Display;
			if (string.IsNullOrEmpty(text6))
			{
				text6 = item;
			}
			if (value == null)
			{
				driftReport.ModChanges.Add("ADDED " + item + " " + value2.Version);
			}
			else if (value2 == null)
			{
				driftReport.ModChanges.Add("REMOVED " + item + " " + value.Version);
			}
			else if (value.Version != value2.Version)
			{
				string value3 = "after " + text6.Replace('_', ' ') + " " + value.Version + " -> " + value2.Version;
				driftReport.ModChanges.Add("UPDATED " + item + " " + value.Version + " -> " + value2.Version);
				dictionary[item] = value3;
			}
			else if (value.Enabled != value2.Enabled)
			{
				driftReport.ModChanges.Add((value2.Enabled ? "ENABLED " : "DISABLED ") + item);
			}
		}
		Dictionary<string, PluginRec> dictionary4 = baseline.Plugins.GroupBy<PluginRec, string>((PluginRec p) => p.Guid, StringComparer.OrdinalIgnoreCase).ToDictionary<IGrouping<string, PluginRec>, string, PluginRec>((IGrouping<string, PluginRec> g) => g.Key, (IGrouping<string, PluginRec> g) => g.First(), StringComparer.OrdinalIgnoreCase);
		Dictionary<string, PluginRec> dictionary5 = now.Plugins.GroupBy<PluginRec, string>((PluginRec p) => p.Guid, StringComparer.OrdinalIgnoreCase).ToDictionary<IGrouping<string, PluginRec>, string, PluginRec>((IGrouping<string, PluginRec> g) => g.Key, (IGrouping<string, PluginRec> g) => g.First(), StringComparer.OrdinalIgnoreCase);
		foreach (string item2 in dictionary4.Keys.Union<string>(dictionary5.Keys, StringComparer.OrdinalIgnoreCase).OrderBy<string, string>((string x) => x, StringComparer.OrdinalIgnoreCase))
		{
			dictionary4.TryGetValue(item2, out var value4);
			dictionary5.TryGetValue(item2, out var value5);
			if (value4 == null)
			{
				driftReport.ModChanges.Add("PLUGIN ADDED " + value5.Name + " (" + item2 + ") " + value5.Version);
				continue;
			}
			if (value5 == null)
			{
				driftReport.ModChanges.Add("PLUGIN GONE " + value4.Name + " (" + item2 + ") " + value4.Version + " (removed or failed to load)");
				continue;
			}
			string key = Manifest.PluginFolder(value5.Path) ?? item2;
			if (value4.Version != value5.Version)
			{
				if (!dictionary.ContainsKey(key))
				{
					driftReport.ModChanges.Add("PLUGIN UPDATED " + value5.Name + " (" + item2 + ") " + value4.Version + " -> " + value5.Version);
					dictionary[key] = "after " + value5.Name + " " + value4.Version + " -> " + value5.Version;
				}
			}
			else if (value4.Hash != value5.Hash && value4.Hash != "pending" && value5.Hash != "pending" && value4.Hash != "" && value5.Hash != "")
			{
				driftReport.ModChanges.Add("PLUGIN REBUILT " + value5.Name + " (" + item2 + ") " + value5.Version + ": same version, different DLL (" + Util.Short(value4.Hash) + " -> " + Util.Short(value5.Hash) + ")");
			}
		}
		foreach (string item3 in new SortedSet<string>(baseline.Details.Keys.Concat(now.Details.Keys), StringComparer.OrdinalIgnoreCase))
		{
			Level level = rules.FileLevel(item3);
			if (level == Level.Ignored)
			{
				continue;
			}
			baseline.Details.TryGetValue(item3, out var value6);
			now.Details.TryGetValue(item3, out var value7);
			PluginRec pluginRec = FindOwner(item3, value7 ?? value6, now);
			driftReport.FileOwners[item3] = pluginRec?.Name;
			string text7 = "";
			if (pluginRec != null)
			{
				string key2 = Manifest.PluginFolder(pluginRec.Path) ?? pluginRec.Guid;
				if (dictionary.TryGetValue(key2, out var value8))
				{
					text7 = value8;
				}
			}
			Level level2 = ((level == Level.Info && !rules.IsHostSyncedFile(item3)) ? Level.Info : Level.Mismatch);
			if (value6 == null)
			{
				driftReport.Items.Add(new DriftItem
				{
					Flag = "NEW FILE",
					Prio = 6,
					File = item3,
					Group = text7,
					Level = level2,
					Note = value7.KeyCount + " keys"
				});
			}
			else if (value7 == null)
			{
				driftReport.Items.Add(new DriftItem
				{
					Flag = "REMOVED FILE",
					Prio = 7,
					File = item3,
					Group = text7,
					Level = level2
				});
			}
			else if (!(value6.Hash == value7.Hash) || !(value6.Kind == value7.Kind))
			{
				if (value6.Kind == "raw" || value7.Kind == "raw")
				{
					driftReport.Items.Add(new DriftItem
					{
						Flag = "CHANGED",
						Prio = 5,
						File = item3,
						Group = text7,
						Level = level2,
						Note = "file content (not a BepInEx config)"
					});
				}
				else
				{
					CompareFile(driftReport, item3, value6, value7, rules, text7, level);
				}
			}
		}
		return driftReport;
	}

	private static void CompareFile(DriftReport r, string path, CfgFile a, CfgFile b, Rules rules, string group, Level fileLevel)
	{
		Dictionary<string, CfgEntry> dictionary = ById(b);
		Dictionary<string, CfgEntry> dictionary2 = ById(a);
		List<CfgEntry> list = new List<CfgEntry>();
		List<CfgEntry> list2 = new List<CfgEntry>();
		int num = 0;
		int num2 = 0;
		List<DriftItem> list3 = new List<DriftItem>();
		foreach (CfgEntry entry in a.Entries)
		{
			if (rules.IsIgnoredKey(path, entry))
			{
				continue;
			}
			dictionary.TryGetValue(entry.Id, out var value);
			if (value != null && rules.IsIgnoredKey(path, value))
			{
				continue;
			}
			Level level = DriftLevel(rules, path, entry.Section, entry.Key, fileLevel);
			bool flag = !entry.Orphan && entry.HasDefault && !entry.IsDefault;
			if (flag && level == Level.Mismatch)
			{
				num++;
			}
			if (value == null || (value.Orphan && !entry.Orphan))
			{
				if (!entry.Orphan)
				{
					list.Add(entry);
				}
			}
			else
			{
				if (CfgParser.SameValue(entry, value))
				{
					continue;
				}
				string text = value.Default ?? entry.Default ?? "";
				bool num3 = value.HasDefault && value.IsDefault;
				bool flag2 = entry.IsDefault || (value.HasDefault && CfgParser.SameValue(value.Type ?? entry.Type, entry.Value, value.Default));
				DriftItem driftItem = new DriftItem
				{
					File = path,
					Section = entry.Section,
					Key = entry.Key,
					Baseline = entry.Value,
					Now = value.Value,
					Default = text,
					Group = group,
					Level = level
				};
				if (num3 && !flag2)
				{
					driftItem.Flag = "LIKELY RESET";
					driftItem.Prio = 0;
					if (level == Level.Mismatch && flag)
					{
						num2++;
					}
				}
				else
				{
					driftItem.Flag = "CHANGED";
					driftItem.Prio = 3;
				}
				if (entry.HasDefault && value.HasDefault && !CfgParser.SameValue(value.Type, entry.Default, value.Default))
				{
					driftItem.Note = "default changed " + entry.Default + " -> " + value.Default;
				}
				list3.Add(driftItem);
			}
		}
		foreach (CfgEntry entry2 in b.Entries)
		{
			if (!entry2.Orphan && !rules.IsIgnoredKey(path, entry2) && (!dictionary2.TryGetValue(entry2.Id, out var value2) || value2.Orphan))
			{
				list2.Add(entry2);
			}
		}
		HashSet<CfgEntry> hashSet = new HashSet<CfgEntry>();
		foreach (CfgEntry item in list)
		{
			dictionary.TryGetValue(item.Id, out var value3);
			bool flag3 = value3?.Orphan ?? false;
			CfgEntry cfgEntry = null;
			if (flag3)
			{
				foreach (CfgEntry item2 in list2)
				{
					if (!hashSet.Contains(item2) && string.Equals(item2.Section, item.Section, StringComparison.OrdinalIgnoreCase) && item2.IsDefault)
					{
						cfgEntry = item2;
						break;
					}
				}
			}
			Level level2 = DriftLevel(rules, path, item.Section, item.Key, fileLevel);
			if (cfgEntry != null)
			{
				hashSet.Add(cfgEntry);
				list3.Add(new DriftItem
				{
					Flag = "POSSIBLY RENAMED",
					Prio = 2,
					File = path,
					Section = item.Section,
					Key = item.Key + " -> " + cfgEntry.Key + "?",
					Baseline = item.Value,
					Now = cfgEntry.Value,
					Default = (cfgEntry.Default ?? ""),
					Group = group,
					Level = level2,
					Note = "old value " + item.Value + ", new value = default " + cfgEntry.Default
				});
			}
			else
			{
				list3.Add(new DriftItem
				{
					Flag = "REMOVED KEY",
					Prio = 5,
					File = path,
					Section = item.Section,
					Key = item.Key,
					Baseline = item.Value,
					Now = (flag3 ? value3.Value : "(gone)"),
					Default = (item.Default ?? ""),
					Group = group,
					Level = level2,
					Note = (flag3 ? "now orphaned: the mod no longer uses it" : "")
				});
			}
		}
		foreach (CfgEntry item3 in list2)
		{
			if (!hashSet.Contains(item3))
			{
				list3.Add(new DriftItem
				{
					Flag = "NEW KEY",
					Prio = 4,
					File = path,
					Section = item3.Section,
					Key = item3.Key,
					Baseline = "(none)",
					Now = item3.Value,
					Default = (item3.Default ?? ""),
					Group = group,
					Level = DriftLevel(rules, path, item3.Section, item3.Key, fileLevel)
				});
			}
		}
		if (num >= 2 && num2 * 2 >= num)
		{
			r.Items.Add(new DriftItem
			{
				Flag = "FILE REGENERATED",
				Prio = 1,
				File = path,
				Group = group,
				Note = num2 + " of " + num + " changed settings back at default"
			});
		}
		r.Items.AddRange(list3);
	}

	internal static Level DriftLevel(Rules rules, string path, string section, string key, Level fileLevel)
	{
		if (fileLevel == Level.Info && !rules.IsHostSyncedFile(path))
		{
			return Level.Info;
		}
		foreach (string infoKeyPattern in rules.InfoKeyPatterns)
		{
			if (Util.Wild(infoKeyPattern, key))
			{
				return Level.Info;
			}
		}
		return Level.Mismatch;
	}

	private static Dictionary<string, CfgEntry> ById(CfgFile f)
	{
		Dictionary<string, CfgEntry> dictionary = new Dictionary<string, CfgEntry>(StringComparer.OrdinalIgnoreCase);
		foreach (CfgEntry entry in f.Entries)
		{
			if (!dictionary.ContainsKey(entry.Id))
			{
				dictionary[entry.Id] = entry;
			}
		}
		return dictionary;
	}

	internal static PluginRec FindOwner(string path, CfgFile f, Manifest m)
	{
		if (f != null && !string.IsNullOrEmpty(f.OwnerGuid))
		{
			foreach (PluginRec plugin in m.Plugins)
			{
				if (string.Equals(plugin.Guid, f.OwnerGuid, StringComparison.OrdinalIgnoreCase))
				{
					return plugin;
				}
			}
		}
		int num = path.LastIndexOf('/');
		string text = ((num > 0) ? path.Substring(0, path.IndexOf('/')) : null);
		string text2 = ((num >= 0) ? path.Substring(num + 1) : path);
		int num2 = text2.LastIndexOf('.');
		string text3 = ((num2 > 0) ? text2.Substring(0, num2) : text2);
		int num3 = text3.IndexOf('.');
		string item = ((num3 > 0) ? text3.Substring(0, num3) : text3);
		List<string> list = new List<string>();
		if (f != null && !string.IsNullOrEmpty(f.OwnerName))
		{
			list.Add(f.OwnerName);
		}
		list.Add(text3);
		if (text != null)
		{
			list.Add(text);
		}
		list.Add(item);
		foreach (string item2 in list)
		{
			string text4 = Squash(item2);
			if (text4.Length < 3)
			{
				continue;
			}
			foreach (PluginRec plugin2 in m.Plugins)
			{
				if (string.Equals(plugin2.Guid, item2, StringComparison.OrdinalIgnoreCase) || Squash(plugin2.Name) == text4)
				{
					return plugin2;
				}
			}
		}
		return null;
	}

	private static string Squash(string s)
	{
		StringBuilder stringBuilder = new StringBuilder();
		string text = s ?? "";
		foreach (char c in text)
		{
			if (char.IsLetterOrDigit(c))
			{
				stringBuilder.Append(char.ToLowerInvariant(c));
			}
		}
		return stringBuilder.ToString();
	}
}
internal static class GameCheck
{
	internal static string Text(string guid, string acs)
	{
		return "PackCheck: game files don't match the expected build (build " + guid + ((acs != null) ? (", Assembly-CSharp " + Util.Short(acs)) : "") + "). Steam may have updated the game.";
	}

	internal static string Mismatch(Manifest m, string expGuid, string expAcs)
	{
		string text = m.G("buildGuid");
		string text2 = m.G("assemblyCSharp");
		bool num = expGuid.Length > 0 && text != "" && !string.Equals(text, expGuid, StringComparison.OrdinalIgnoreCase);
		bool flag = expAcs.Length > 0 && text2 != "" && text2 != "pending" && !string.Equals(text2, expAcs, StringComparison.OrdinalIgnoreCase);
		if (!num && !flag)
		{
			return null;
		}
		return Text(text, flag ? text2 : null);
	}
}
internal static class Hashing
{
	internal struct PluginKey
	{
		public string Guid;

		public string Version;

		public string Hash;
	}

	internal const string Pending = "pending";

	internal const string SizeOnly = "-";

	internal static string Sha256Hex(byte[] data)
	{
		using SHA256 sHA = SHA256.Create();
		return Util.Hex(sHA.ComputeHash(data));
	}

	internal static string Sha256Hex(string text)
	{
		return Sha256Hex(Encoding.UTF8.GetBytes(text ?? ""));
	}

	internal static string Sha256File(string path)
	{
		int num = 0;
		while (true)
		{
			try
			{
				using FileStream inputStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 65536);
				using SHA256 sHA = SHA256.Create();
				return Util.Hex(sHA.ComputeHash(inputStream));
			}
			catch (IOException) when (num < 3 && File.Exists(path))
			{
				Thread.Sleep(200);
			}
			num++;
		}
	}

	internal static byte[] ReadAllShared(string path)
	{
		int num = 0;
		while (true)
		{
			try
			{
				using FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
				MemoryStream memoryStream = new MemoryStream((int)Math.Max(0L, Math.Min(fileStream.Length, 2147483647L)));
				fileStream.CopyTo(memoryStream);
				return memoryStream.ToArray();
			}
			catch (IOException) when (num < 3 && File.Exists(path))
			{
				Thread.Sleep(200);
			}
			num++;
		}
	}

	internal static string Combine(IEnumerable<string> lines)
	{
		List<string> list = new List<string>(lines);
		list.Sort(StringComparer.OrdinalIgnoreCase);
		StringBuilder stringBuilder = new StringBuilder();
		foreach (string item in list)
		{
			stringBuilder.Append(item).Append('\n');
		}
		return Sha256Hex(stringBuilder.ToString());
	}

	internal static string Fingerprint(string buildGuid, string acsHash, IEnumerable<PluginKey> plugins, ICollection<string> allowedExtra)
	{
		if (acsHash == "pending")
		{
			return "pending";
		}
		List<string> list = new List<string>();
		foreach (PluginKey plugin in plugins)
		{
			if (allowedExtra == null || !Contains(allowedExtra, plugin.Guid))
			{
				if (plugin.Hash == "pending")
				{
					return "pending";
				}
				list.Add((plugin.Guid ?? "").ToLowerInvariant() + "|" + plugin.Version + "|" + plugin.Hash);
			}
		}
		list.Sort(StringComparer.Ordinal);
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append((buildGuid ?? "").ToLowerInvariant()).Append('\n').Append(acsHash ?? "")
			.Append('\n');
		foreach (string item in list)
		{
			stringBuilder.Append(item).Append('\n');
		}
		return Sha256Hex(stringBuilder.ToString()).Substring(0, 16);
	}

	internal static bool Contains(ICollection<string> list, string s)
	{
		foreach (string item in list)
		{
			if (string.Equals(item, s, StringComparison.OrdinalIgnoreCase))
			{
				return true;
			}
		}
		return false;
	}
}
internal class HashCache
{
	private struct Entry
	{
		public long Size;

		public long Ticks;

		public string Hash;
	}

	private readonly Dictionary<string, Entry> _map = new Dictionary<string, Entry>(StringComparer.OrdinalIgnoreCase);

	private readonly object _lock = new object();

	private bool _dirty;

	internal int Hits;

	internal int Misses;

	internal long BytesHashed;

	internal void Load(string file)
	{
		try
		{
			if (!File.Exists(file))
			{
				return;
			}
			string[] array = File.ReadAllLines(file);
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Split('\t');
				if (array2.Length >= 4 && long.TryParse(array2[1], out var result) && long.TryParse(array2[2], out var result2))
				{
					lock (_lock)
					{
						_map[array2[3]] = new Entry
						{
							Hash = array2[0],
							Size = result,
							Ticks = result2
						};
					}
				}
			}
		}
		catch
		{
		}
	}

	internal void Save(string file)
	{
		List<string> list;
		lock (_lock)
		{
			if (!_dirty)
			{
				return;
			}
			list = new List<string>(_map.Count);
			foreach (KeyValuePair<string, Entry> item in _map)
			{
				list.Add(item.Value.Hash + "\t" + item.Value.Size + "\t" + item.Value.Ticks + "\t" + item.Key);
			}
			_dirty = false;
		}
		list.Sort(StringComparer.OrdinalIgnoreCase);
		Files.WriteAtomic(file, string.Join("\n", list) + "\n");
	}

	internal string Get(string path)
	{
		FileInfo fileInfo = new FileInfo(path);
		if (!fileInfo.Exists)
		{
			return null;
		}
		long length = fileInfo.Length;
		long ticks = fileInfo.LastWriteTimeUtc.Ticks;
		lock (_lock)
		{
			if (_map.TryGetValue(path, out var value) && value.Size == length && value.Ticks == ticks)
			{
				Hits++;
				return value.Hash;
			}
		}
		string text = Hashing.Sha256File(path);
		lock (_lock)
		{
			_map[path] = new Entry
			{
				Hash = text,
				Size = length,
				Ticks = ticks
			};
			_dirty = true;
			Misses++;
			BytesHashed += length;
			return text;
		}
	}

	internal void ResetCounters()
	{
		lock (_lock)
		{
			Hits = 0;
			Misses = 0;
			BytesHashed = 0L;
		}
	}
}
internal static class Files
{
	internal static void WriteAtomic(string path, string text)
	{
		string directoryName = Path.GetDirectoryName(path);
		if (!string.IsNullOrEmpty(directoryName))
		{
			Directory.CreateDirectory(directoryName);
		}
		string text2 = path + ".tmp";
		File.WriteAllText(text2, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
		if (File.Exists(path))
		{
			try
			{
				File.Replace(text2, path, null);
				return;
			}
			catch
			{
			}
			File.Delete(path);
		}
		File.Move(text2, path);
	}

	internal static void Prune(string dir, string prefix, string suffix, int keep, string except = null)
	{
		try
		{
			if (!Directory.Exists(dir))
			{
				return;
			}
			List<string> list = new List<string>();
			string[] files = Directory.GetFiles(dir, prefix + "*" + suffix);
			foreach (string text in files)
			{
				string fileName = Path.GetFileName(text);
				if ((except == null || !string.Equals(fileName, except, StringComparison.OrdinalIgnoreCase)) && fileName.IndexOf("latest", StringComparison.OrdinalIgnoreCase) < 0)
				{
					list.Add(text);
				}
			}
			list.Sort(StringComparer.OrdinalIgnoreCase);
			for (int j = 0; j < list.Count - Math.Max(0, keep); j++)
			{
				try
				{
					File.Delete(list[j]);
				}
				catch
				{
				}
			}
		}
		catch
		{
		}
	}
}
internal static class Hooks
{
	private static int _errors;

	private static void Fail(string where, Exception e)
	{
		if (++_errors <= 5)
		{
			Plugin.Log.LogWarning((object)(where + ": " + e.Message));
		}
	}

	internal static void AfterSetConnectionData(GameNetworkManager __instance)
	{
		try
		{
			if (!Plugin.SendJoinFingerprint.Value || (Object)(object)__instance == (Object)null || __instance.disableSteam)
			{
				return;
			}
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && singleton.NetworkConfig != null && singleton.NetworkConfig.ConnectionData != null)
			{
				string text = Encoding.ASCII.GetString(singleton.NetworkConfig.ConnectionData);
				if (text.Split(',').Length != 2)
				{
					Plugin.Log.LogInfo((object)"Join request payload isn't the usual \"version,steamId\"; not adding the fingerprint.");
					return;
				}
				string fingerprint = Core.Fingerprint;
				singleton.NetworkConfig.ConnectionData = Encoding.ASCII.GetBytes(text + ",PC1:" + fingerprint);
				Plugin.Log.LogInfo((object)("Added pack fingerprint PC1:" + fingerprint + " to the join request."));
			}
		}
		catch (Exception e)
		{
			Fail("Join fingerprint", e);
		}
	}

	internal static void AfterConnectionApproval(ConnectionApprovalRequest __0, ConnectionApprovalResponse __1)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			Net.OnApproval(__0.ClientNetworkId, __0.Payload, __1?.Approved ?? false, (__1 != null) ? __1.Reason : "");
		}
		catch (Exception e)
		{
			Fail("Join fingerprint check", e);
		}
	}

	internal static void AfterMenuStart(MenuManager __instance)
	{
		try
		{
			if (!((Object)(object)__instance == (Object)null) && !__instance.isInitScene)
			{
				Runner.Menu = __instance;
				Core.OnMainMenu();
				Runner.ShowQueuedPopup();
			}
		}
		catch (Exception e)
		{
			Fail("Main menu check", e);
		}
	}

	internal static void AfterStartOfRoundStart()
	{
		try
		{
			Core.OnLobby();
		}
		catch (Exception e)
		{
			Fail("Lobby check", e);
		}
	}
}
internal class DiffItem
{
	public Level Level;

	public int Cat;

	public string Group = "";

	public string GroupName = "";

	public int Prio;

	public string Chat = "";

	public string Full = "";
}
internal class JoinInput
{
	public Manifest Host;

	public Manifest Client;

	public Dictionary<string, CfgFile> HostDetail = new Dictionary<string, CfgFile>(StringComparer.OrdinalIgnoreCase);

	public Dictionary<string, CfgFile> ClientDetail = new Dictionary<string, CfgFile>(StringComparer.OrdinalIgnoreCase);

	public bool DetailReceived;

	public Rules Rules;

	public string HostName = "you";

	public string ClientName = "friend";

	public string Stage0 = "";

	public List<string> NetSyncGuard = new List<string>();

	public string Timing = "";

	public string RerunKey = "Shift+F9";

	public string FileName = "BepInEx/PackCheck/join-latest.txt";

	public DateTime Time = DateTime.Now;

	public string HostVersion = "";
}
internal class JoinReport
{
	public List<DiffItem> Items = new List<DiffItem>();

	public List<string> Notes = new List<string>();

	public List<string> IgnoredList = new List<string>();

	public int GameMismatches;

	public int ModGroups;

	public int ConfigGroups;

	public int InfoCount;

	public int PluginCount;

	public int PackageCount;

	public int ConfigCount;

	public bool HostPending;

	public bool ClientPending;

	public string Version = "";

	public bool SameBuild;

	public JoinInput Input;

	public bool Matches
	{
		get
		{
			if (GameMismatches == 0 && ModGroups == 0)
			{
				return ConfigGroups == 0;
			}
			return false;
		}
	}

	public string MatchLine()
	{
		string text = Input.ClientName + " matches: game v" + ((Version == "") ? "?" : Version) + (SameBuild ? " (same build)" : "") + ", " + PluginCount + " plugins, " + PackageCount + " packages, " + ConfigCount + " configs.";
		if (InfoCount > 0)
		{
			text = text + " " + InfoCount + " info difference" + ((InfoCount == 1) ? "" : "s") + " in " + Input.FileName + ".";
		}
		return text;
	}

	public string Counts()
	{
		List<string> list = new List<string>();
		if (GameMismatches > 0)
		{
			list.Add("game files differ");
		}
		List<string> list2 = new List<string>();
		if (ModGroups > 0)
		{
			list2.Add(ModGroups + " mod");
		}
		if (ConfigGroups > 0)
		{
			list2.Add(ConfigGroups + " config");
		}
		if (list2.Count > 0)
		{
			list.Add(string.Join(" and ", list2.ToArray()) + " difference" + ((ModGroups + ConfigGroups == 1) ? "" : "s"));
		}
		if (list.Count == 0)
		{
			list.Add("no differences");
		}
		return string.Join(", ", list.ToArray());
	}

	public string Tip()
	{
		return Input.ClientName + ": " + Counts() + ". See chat.";
	}

	public List<List<DiffItem>> MismatchGroups()
	{
		return (from g in Items.Where((DiffItem i) => i.Level == Level.Mismatch).GroupBy<DiffItem, string>((DiffItem i) => i.Group, StringComparer.OrdinalIgnoreCase)
			select g.OrderBy((DiffItem i) => i.Prio).ToList() into g
			orderby g[0].Cat, g[0].Prio
			select g).ThenBy<List<DiffItem>, string>((List<DiffItem> g) => g[0].GroupName, StringComparer.OrdinalIgnoreCase).ToList();
	}

	public List<string> ChatLines(int max)
	{
		List<string> list = new List<string>();
		if (max <= 0)
		{
			return list;
		}
		if (Matches)
		{
			list.Add(MatchLine());
			if (HostPending || ClientPending)
			{
				list.Add(PendingLine());
			}
			return list.Take(max).ToList();
		}
		List<List<DiffItem>> list2 = MismatchGroups();
		List<string> list3 = new List<string>();
		if (HostPending || ClientPending)
		{
			list3.Add(PendingLine());
		}
		foreach (List<DiffItem> item in list2)
		{
			string text = ((item[0].Cat == 3) ? ConfigChat(item) : item[0].Chat);
			if (item[0].Cat != 3 && item.Count > 1)
			{
				text = text + " (+" + (item.Count - 1) + " more)";
			}
			list3.Add(text);
		}
		string text2 = ((InfoCount > 0) ? (InfoCount + " info difference" + ((InfoCount == 1) ? "" : "s") + " (not counted)") : null);
		if (list3.Count <= max)
		{
			list.AddRange(list3);
			if (text2 != null && list.Count < max)
			{
				list.Add(text2 + ": " + Input.FileName);
			}
			return list;
		}
		list.AddRange(list3.Take(max - 1));
		int num = list3.Count - (max - 1);
		list.Add("...and " + num + " more" + ((text2 != null) ? (", plus " + text2) : "") + ": " + Input.FileName);
		return list;
	}

	private string PendingLine()
	{
		string text = ((HostPending && ClientPending) ? "both sides" : (HostPending ? "your side" : (Input.ClientName + "'s side")));
		return "Some hashes still pending on " + text + ". Press " + Input.RerunKey + " to re-run.";
	}

	private static string ConfigChat(List<DiffItem> g)
	{
		List<DiffItem> list = g.Where((DiffItem i) => i.Prio >= 10).ToList();
		if (list.Count == 0)
		{
			return g[0].Chat;
		}
		string text = string.Join(", ", (from i in list.Take(2)
			select i.Chat).ToArray());
		return g[0].GroupName + ": " + list.Count + ((list.Count == 1) ? " key differs (" : " keys differ (") + text + ((list.Count > 2) ? " ..." : "") + ")";
	}

	public string[] Summary(int max)
	{
		if (Matches && !HostPending && !ClientPending)
		{
			return new string[1] { MatchLine() };
		}
		List<string> list = new List<string>();
		list.Add(Tip());
		list.AddRange(ChatLines(Math.Max(1, max)));
		return list.ToArray();
	}

	public string FullText()
	{
		JoinInput input = Input;
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append("PackCheck ").Append(input.HostVersion).Append(" join report, ")
			.Append(input.Time.ToString("yyyy-MM-dd HH:mm:ss", Util.Inv))
			.Append(" (local time)\n");
		stringBuilder.Append("You (host): ").Append(input.HostName).Append(", profile ")
			.Append(input.Host.H("profile"))
			.Append(", PackCheck ")
			.Append(input.Host.H("version"))
			.Append('\n');
		stringBuilder.Append("Them (client): ").Append(input.ClientName).Append(", profile ")
			.Append(input.Client.H("profile"))
			.Append(", PackCheck ")
			.Append(input.Client.H("version"))
			.Append('\n');
		stringBuilder.Append("Result: ").Append(Matches ? "MATCH" : Counts()).Append(". ")
			.Append(InfoCount)
			.Append(" info, ")
			.Append(IgnoredList.Count)
			.Append(" ignored.\n");
		foreach (string note in Notes)
		{
			stringBuilder.Append("Note: ").Append(note).Append('\n');
		}
		stringBuilder.Append("\n== Join fingerprint (stage 0)\n").Append(string.IsNullOrEmpty(input.Stage0) ? "(none recorded)" : input.Stage0).Append('\n');
		stringBuilder.Append("\n== Game\n");
		foreach (string item in new SortedSet<string>(input.Host.Game.Keys.Concat(input.Client.Game.Keys), StringComparer.OrdinalIgnoreCase))
		{
			string text = input.Host.G(item);
			string text2 = input.Client.G(item);
			stringBuilder.Append((text == text2) ? "  " : "* ").Append(item).Append(" | you: ")
				.Append(text)
				.Append(" | them: ")
				.Append(text2)
				.Append('\n');
		}
		string[] array = new string[4] { "Game", "Mods (plugins, packages, DLLs)", "Our own mods", "Configs" };
		stringBuilder.Append("\n== Mismatches\n");
		if (Matches)
		{
			stringBuilder.Append("(none)\n");
		}
		int c;
		for (c = 0; c < 4; c++)
		{
			List<DiffItem> list = Items.Where((DiffItem x) => x.Level == Level.Mismatch && x.Cat == c).OrderBy<DiffItem, string>((DiffItem x) => x.GroupName, StringComparer.OrdinalIgnoreCase).ThenBy((DiffItem x) => x.Prio)
				.ToList();
			if (list.Count == 0)
			{
				continue;
			}
			stringBuilder.Append("-- ").Append(array[c]).Append('\n');
			foreach (DiffItem item2 in list)
			{
				stringBuilder.Append(item2.Full).Append('\n');
			}
		}
		if (Items.Any((DiffItem x) => x.Cat == 3))
		{
			stringBuilder.Append("(config lines: file | [section] key | you | them | default | flags)\n");
		}
		stringBuilder.Append("\n== Info (shown, not counted)\n");
		List<DiffItem> list2 = (from x in Items
			where x.Level == Level.Info
			orderby x.Cat
			select x).ThenBy<DiffItem, string>((DiffItem x) => x.GroupName, StringComparer.OrdinalIgnoreCase).ToList();
		if (list2.Count == 0)
		{
			stringBuilder.Append("(none)\n");
		}
		foreach (DiffItem item3 in list2)
		{
			stringBuilder.Append(item3.Full).Append('\n');
		}
		stringBuilder.Append("\n== NetSyncGuard during this join\n");
		if (input.NetSyncGuard.Count == 0)
		{
			stringBuilder.Append("No repairs logged.\n");
		}
		else
		{
			stringBuilder.Append("NetSyncGuard repaired ").Append(input.NetSyncGuard.Count).Append(" object(s):\n");
			foreach (string item4 in input.NetSyncGuard)
			{
				stringBuilder.Append("  ").Append(item4).Append('\n');
			}
		}
		stringBuilder.Append("\n== Timing\n").Append(input.Timing).Append('\n');
		stringBuilder.Append("\n== Ignored (").Append(IgnoredList.Count).Append(")\n");
		foreach (string ignored in IgnoredList)
		{
			stringBuilder.Append("  ").Append(ignored).Append('\n');
		}
		return stringBuilder.ToString();
	}
}
internal static class JoinDiff
{
	internal static readonly string[] GameKeysMismatch = new string[9] { "versionNum", "buildGuid", "assemblyCSharp", "exe", "unityPlayer", "managed", "dataListing", "unityVersion", "bepinexVersion" };

	internal static readonly string[] GameKeysInfo = new string[3] { "steamBuildId", "steamBeta", "copy" };

	internal static JoinReport Compare(JoinInput inp)
	{
		JoinReport joinReport = new JoinReport
		{
			Input = inp
		};
		Manifest host = inp.Host;
		Manifest client = inp.Client;
		Rules rules = inp.Rules;
		joinReport.HostPending = host.AnyPending;
		joinReport.ClientPending = client.AnyPending;
		joinReport.Version = host.G("versionNum");
		joinReport.SameBuild = host.G("buildGuid") != "" && host.G("buildGuid") == client.G("buildGuid");
		if (host.H("protocol") != client.H("protocol") && client.H("protocol") != "")
		{
			joinReport.Notes.Add("PackCheck versions differ (you " + host.H("version") + ", them " + client.H("version") + "); compared whatever parsed.");
		}
		CompareGame(joinReport, host, client);
		ComparePlugins(joinReport, host, client, rules);
		ComparePackages(joinReport, host, client);
		CompareConfigs(joinReport, inp);
		joinReport.GameMismatches = joinReport.Items.Count((DiffItem x) => x.Level == Level.Mismatch && x.Cat == 0);
		joinReport.ModGroups = (from x in joinReport.Items
			where x.Level == Level.Mismatch && (x.Cat == 1 || x.Cat == 2)
			select x.Group).Distinct<string>(StringComparer.OrdinalIgnoreCase).Count();
		joinReport.ConfigGroups = (from x in joinReport.Items
			where x.Level == Level.Mismatch && x.Cat == 3
			select x.Group).Distinct<string>(StringComparer.OrdinalIgnoreCase).Count();
		joinReport.InfoCount = joinReport.Items.Count((DiffItem x) => x.Level == Level.Info);
		joinReport.PluginCount = host.Plugins.Count;
		joinReport.PackageCount = (host.HasModsYml ? host.PackagesFrom("yml").Count : host.PackagesFrom("manifest").Count);
		return joinReport;
	}

	private static void Add(JoinReport r, Level lvl, int cat, string group, string groupName, int prio, string chat, string full)
	{
		r.Items.Add(new DiffItem
		{
			Level = lvl,
			Cat = cat,
			Group = group,
			GroupName = groupName,
			Prio = prio,
			Chat = chat,
			Full = full
		});
	}

	private static void CompareGame(JoinReport r, Manifest H, Manifest C)
	{
		int num = 0;
		string[] gameKeysMismatch = GameKeysMismatch;
		foreach (string text in gameKeysMismatch)
		{
			num++;
			string text2 = H.G(text);
			string text3 = C.G(text);
			if (!(text2 == text3) && (!(text2 == "") || !(text3 == "")) && !(text2 == "pending") && !(text3 == "pending"))
			{
				string chat;
				switch (text)
				{
				case "buildGuid":
					chat = "Game build differs (you " + Util.Short(text2) + ", them " + Util.Short(text3) + ")";
					break;
				case "versionNum":
					chat = "Game version differs (you v" + text2 + ", them v" + text3 + ")";
					break;
				case "unityVersion":
				case "bepinexVersion":
					chat = ((text == "unityVersion") ? "Unity" : "BepInEx") + " version differs (you " + text2 + ", them " + text3 + ")";
					break;
				default:
					chat = "Game files differ: " + text + " (you " + Util.Short(text2) + ", them " + Util.Short(text3) + ")";
					break;
				}
				Add(r, Level.Mismatch, 0, "game", "Game", num, chat, "[game] " + text + " | you: " + text2 + " | them: " + text3);
			}
		}
		gameKeysMismatch = GameKeysInfo;
		foreach (string text4 in gameKeysMismatch)
		{
			string text5 = H.G(text4);
			string text6 = C.G(text4);
			if (!(text5 == text6))
			{
				Add(r, Level.Info, 0, "game", "Game", 50, "Game " + text4 + " differs", "[game] " + text4 + " | you: " + text5 + " | them: " + text6 + " (info only)");
			}
		}
	}

	private static string ModGroup(string path, string fallback)
	{
		string text = Manifest.PluginFolder(path);
		if (text != null)
		{
			return "mod:" + text;
		}
		return "mod:" + fallback;
	}

	private static void ComparePlugins(JoinReport r, Manifest H, Manifest C, Rules rules)
	{
		Dictionary<string, PluginRec> dictionary = ToDict(H.Plugins);
		Dictionary<string, PluginRec> dictionary2 = ToDict(C.Plugins);
		HashSet<string> hashSet = new HashSet<string>(H.Dlls.Select((FileRec d) => d.Path), StringComparer.OrdinalIgnoreCase);
		HashSet<string> hashSet2 = new HashSet<string>(C.Dlls.Select((FileRec d) => d.Path), StringComparer.OrdinalIgnoreCase);
		HashSet<string> hashSet3 = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
		foreach (PluginRec item in H.Plugins.Concat(C.Plugins))
		{
			if (rules.IsAllowedExtra(item.Guid))
			{
				string text = Manifest.PluginFolder(item.Path);
				if (text != null)
				{
					hashSet3.Add(text);
				}
			}
		}
		HashSet<string> hashSet4 = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
		foreach (FileRec item2 in H.OwnFiles.Concat(C.OwnFiles))
		{
			string text2 = Manifest.PluginFolder(item2.Path);
			if (text2 != null)
			{
				hashSet4.Add(text2);
			}
		}
		HashSet<string> hashSet5 = new HashSet<string>(from p in H.Plugins.Concat(C.Plugins)
			select p.Path, StringComparer.OrdinalIgnoreCase);
		foreach (string item3 in dictionary.Keys.Union<string>(dictionary2.Keys, StringComparer.OrdinalIgnoreCase).OrderBy<string, string>((string g) => g, StringComparer.OrdinalIgnoreCase))
		{
			dictionary.TryGetValue(item3, out var value);
			dictionary2.TryGetValue(item3, out var value2);
			PluginRec pluginRec = value ?? value2;
			string text3 = Manifest.PluginFolder(pluginRec.Path);
			bool flag = item3.StartsWith("jacob.", StringComparison.OrdinalIgnoreCase) || (text3 != null && rules.IsOwnFolder(text3));
			int cat = ((!flag) ? 1 : 2);
			string text4 = ModGroup(pluginRec.Path, item3);
			string text5 = (string.IsNullOrEmpty(pluginRec.Name) ? item3 : pluginRec.Name);
			if (value == null || value2 == null)
			{
				string text6 = ((value == null) ? "your" : "their");
				string text7 = ((value == null) ? "them" : "you");
				bool flag2 = ((value == null) ? hashSet.Contains(value2.Path) : hashSet2.Contains(value.Path));
				if (rules.IsAllowedExtra(item3))
				{
					Add(r, Level.Info, cat, text4, text5, 5, text5 + ": only on " + ((value == null) ? "their" : "your") + " side (allowed)", "[plugin] " + text5 + " (" + item3 + ") " + pluginRec.Version + ": only on " + ((value == null) ? "their" : "your") + " side (AllowedExtraPlugins)");
				}
				else if (flag2)
				{
					Add(r, Level.Mismatch, cat, text4, text5, 1, text5 + " " + pluginRec.Version + ": not loaded on " + text6 + " side", "[plugin] " + text5 + " (" + item3 + ") " + pluginRec.Version + ": loaded for " + text7 + ", not loaded on " + text6 + " side although the DLL is there (" + pluginRec.Path + "); missing dependency or failed load, see that side's LogOutput.log");
				}
				else
				{
					Add(r, Level.Mismatch, cat, text4, text5, 0, text5 + " " + pluginRec.Version + ": missing on " + text6 + " side", "[plugin] " + text5 + " (" + item3 + ") " + pluginRec.Version + ": missing on " + text6 + " side (" + pluginRec.Path + ")");
				}
			}
			else if (value.Version != value2.Version)
			{
				Add(r, Level.Mismatch, cat, text4, text5, 1, text5 + ": you " + value.Version + ", them " + value2.Version, "[plugin] " + text5 + " (" + item3 + "): you " + value.Version + " (" + Util.Short(value.Hash) + "), them " + value2.Version + " (" + Util.Short(value2.Hash) + ")");
			}
			else if (value.Hash != value2.Hash && value.Hash != "pending" && value2.Hash != "pending")
			{
				string text8 = (flag ? "" : "; patched or corrupt copy on one side");
				Add(r, Level.Mismatch, cat, text4, text5, 2, text5 + " " + value.Version + ": same version, different build (you " + Util.Short(value.Hash) + ", them " + Util.Short(value2.Hash) + ")", "[plugin] " + text5 + " (" + item3 + ") " + value.Version + ": same version, different build (you " + value.Hash + ", them " + value2.Hash + ")" + text8);
			}
		}
		Dictionary<string, FileRec> dictionary3 = H.Dlls.ToDictionary<FileRec, string>((FileRec d) => d.Path, StringComparer.OrdinalIgnoreCase);
		Dictionary<string, FileRec> dictionary4 = C.Dlls.ToDictionary<FileRec, string>((FileRec d) => d.Path, StringComparer.OrdinalIgnoreCase);
		foreach (string item4 in dictionary3.Keys.Union<string>(dictionary4.Keys, StringComparer.OrdinalIgnoreCase).OrderBy<string, string>((string x) => x, StringComparer.OrdinalIgnoreCase))
		{
			if (hashSet5.Contains(item4))
			{
				continue;
			}
			string text9 = Manifest.PluginFolder(item4);
			if (text9 != null && hashSet4.Contains(text9))
			{
				continue;
			}
			dictionary3.TryGetValue(item4, out var value3);
			dictionary4.TryGetValue(item4, out var value4);
			string text10 = ModGroup(item4, item4);
			string groupName = text9 ?? item4;
			bool flag3 = text9 != null && hashSet3.Contains(text9);
			if (Scanner.IsMmhook(item4))
			{
				if (value3 == null || value4 == null || value3.Size != value4.Size)
				{
					Add(r, Level.Info, 1, "mmhook", "MMHOOK", 50, "MMHOOK differs", "[mmhook] " + item4 + ": " + ((value3 == null) ? "missing on your side" : ((value4 == null) ? "missing on their side" : ("size you " + value3.Size + ", them " + value4.Size))) + " (regenerated per machine, info only)");
				}
			}
			else if (value3 == null || value4 == null)
			{
				string text11 = ((value3 == null) ? "your" : "their");
				Add(r, flag3 ? Level.Info : Level.Mismatch, 1, text10, groupName, 3, Short(item4) + ": missing on " + text11 + " side", "[dll] " + item4 + ": missing on " + text11 + " side");
			}
			else if (value3.Hash != value4.Hash && value3.Hash != "pending" && value4.Hash != "pending")
			{
				Add(r, Level.Mismatch, 1, text10, groupName, 4, Short(item4) + ": different file (you " + Util.Short(value3.Hash) + ", them " + Util.Short(value4.Hash) + ")", "[dll] " + item4 + ": different file (you " + value3.Hash + ", them " + value4.Hash + "); patched or corrupt copy on one side");
			}
		}
		Dictionary<string, FileRec> dictionary5 = H.Assets.ToDictionary<FileRec, string>((FileRec d) => d.Path, StringComparer.OrdinalIgnoreCase);
		Dictionary<string, FileRec> dictionary6 = C.Assets.ToDictionary<FileRec, string>((FileRec d) => d.Path, StringComparer.OrdinalIgnoreCase);
		foreach (string item5 in dictionary5.Keys.Union<string>(dictionary6.Keys, StringComparer.OrdinalIgnoreCase).OrderBy<string, string>((string x) => x, StringComparer.OrdinalIgnoreCase))
		{
			dictionary5.TryGetValue(item5, out var value5);
			dictionary6.TryGetValue(item5, out var value6);
			string text12 = Manifest.PluginFolder(item5) ?? item5;
			string text13 = "mod:" + text12;
			if (value5 == null || value6 == null)
			{
				string text14 = ((value5 == null) ? "your" : "their");
				Add(r, Level.Mismatch, 1, text13, text12, 3, Short(item5) + ": missing on " + text14 + " side", "[asset] " + item5 + ": missing on " + text14 + " side");
			}
			else if (value5.Size != value6.Size)
			{
				Add(r, Level.Mismatch, 1, text13, text12, 4, Short(item5) + ": size differs (you " + value5.Size + ", them " + value6.Size + " bytes)", "[asset] " + item5 + ": size differs (you " + value5.Size + ", them " + value6.Size + " bytes); different version, or a broken download on one side");
			}
		}
		Dictionary<string, FolderRec> dictionary7 = H.Listings.ToDictionary<FolderRec, string>((FolderRec d) => d.Folder, StringComparer.OrdinalIgnoreCase);
		Dictionary<string, FolderRec> dictionary8 = C.Listings.ToDictionary<FolderRec, string>((FolderRec d) => d.Folder, StringComparer.OrdinalIgnoreCase);
		foreach (string item6 in dictionary7.Keys.Intersect<string>(dictionary8.Keys, StringComparer.OrdinalIgnoreCase).OrderBy<string, string>((string x) => x, StringComparer.OrdinalIgnoreCase))
		{
			FolderRec folderRec = dictionary7[item6];
			FolderRec folderRec2 = dictionary8[item6];
			if (!(folderRec.Hash == folderRec2.Hash))
			{
				Add(r, Level.Info, 1, "mod:" + item6, item6, 60, item6 + ": other files differ", "[files] plugins/" + item6 + "/: non-DLL files differ (you " + folderRec.Count + " files, " + folderRec.Bytes + " bytes; them " + folderRec2.Count + " files, " + folderRec2.Bytes + " bytes; sounds, json, docs...; info only)");
			}
		}
		Dictionary<string, FileRec> dictionary9 = H.OwnFiles.ToDictionary<FileRec, string>((FileRec d) => d.Path, StringComparer.OrdinalIgnoreCase);
		Dictionary<string, FileRec> dictionary10 = C.OwnFiles.ToDictionary<FileRec, string>((FileRec d) => d.Path, StringComparer.OrdinalIgnoreCase);
		HashSet<string> hashSet6 = new HashSet<string>(H.OwnFiles.Select((FileRec e) => Manifest.PluginFolder(e.Path) ?? ""), StringComparer.OrdinalIgnoreCase);
		HashSet<string> hashSet7 = new HashSet<string>(C.OwnFiles.Select((FileRec e) => Manifest.PluginFolder(e.Path) ?? ""), StringComparer.OrdinalIgnoreCase);
		HashSet<string> hashSet8 = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
		foreach (string item7 in dictionary9.Keys.Union<string>(dictionary10.Keys, StringComparer.OrdinalIgnoreCase).OrderBy<string, string>((string x) => x, StringComparer.OrdinalIgnoreCase))
		{
			dictionary9.TryGetValue(item7, out var value7);
			dictionary10.TryGetValue(item7, out var value8);
			string text15 = Manifest.PluginFolder(item7) ?? "";
			string text16 = "mod:" + text15;
			bool flag4 = hashSet3.Contains(text15);
			if (value7 == null || value8 == null)
			{
				bool num = ((value7 == null) ? (!hashSet6.Contains(text15)) : (!hashSet7.Contains(text15)));
				string text17 = ((value7 == null) ? "your" : "their");
				if (num)
				{
					if (hashSet8.Add(text15))
					{
						Add(r, flag4 ? Level.Info : Level.Mismatch, 2, text16, text15, 3, text15 + ": folder missing on " + text17 + " side", "[own] plugins/" + text15 + "/: folder missing on " + text17 + " side" + (flag4 ? " (allowed extra plugin)" : ""));
					}
				}
				else
				{
					Add(r, Level.Mismatch, 2, text16, text15, 4, text15 + ": " + FileIn(item7) + " missing on " + text17 + " side", "[own] " + item7 + ": missing on " + text17 + " side");
				}
			}
			else if (value7.Hash != value8.Hash && value7.Hash != "pending" && value8.Hash != "pending")
			{
				Add(r, Level.Mismatch, 2, text16, text15, 5, text15 + ": " + FileIn(item7) + " differs (you " + Util.Short(value7.Hash) + ", them " + Util.Short(value8.Hash) + ")", "[own] " + item7 + ": differs (you " + value7.Hash + ", " + value7.Size + " bytes; them " + value8.Hash + ", " + value8.Size + " bytes)");
			}
		}
	}

	private static string Short(string path)
	{
		int num = path.LastIndexOf('/');
		if (num < 0)
		{
			return path;
		}
		return path.Substring(num + 1);
	}

	private static string FileIn(string path)
	{
		string text = path;
		if (text.StartsWith("plugins/", StringComparison.OrdinalIgnoreCase))
		{
			text = text.Substring(8);
		}
		int num = text.IndexOf('/');
		if (num < 0)
		{
			return text;
		}
		return text.Substring(num + 1);
	}

	private static Dictionary<string, PluginRec> ToDict(List<PluginRec> list)
	{
		Dictionary<string, PluginRec> dictionary = new Dictionary<string, PluginRec>(StringComparer.OrdinalIgnoreCase);
		foreach (PluginRec item in list)
		{
			if (!dictionary.ContainsKey(item.Guid))
			{
				dictionary[item.Guid] = item;
			}
		}
		return dictionary;
	}

	private static void ComparePackages(JoinReport r, Manifest H, Manifest C)
	{
		string source = "yml";
		if (!H.HasModsYml || !C.HasModsYml)
		{
			source = "manifest";
			if (H.HasModsYml != C.HasModsYml)
			{
				r.Notes.Add((H.HasModsYml ? "They have" : "You have") + " no mods.yml (installed from a zip or another manager?): packages compared from manifest.json files.");
			}
		}
		Dictionary<string, PackageRec> dictionary = PkgDict(H.PackagesFrom(source));
		Dictionary<string, PackageRec> dictionary2 = PkgDict(C.PackagesFrom(source));
		foreach (string item in dictionary.Keys.Union<string>(dictionary2.Keys, StringComparer.OrdinalIgnoreCase).OrderBy<string, string>((string x) => x, StringComparer.OrdinalIgnoreCase))
		{
			dictionary.TryGetValue(item, out var value);
			dictionary2.TryGetValue(item, out var value2);
			PackageRec packageRec = value ?? value2;
			string text = (string.IsNullOrEmpty(packageRec.Display) ? item : packageRec.Display.Replace('_', ' '));
			string text2 = "mod:" + item;
			if (value == null || value2 == null)
			{
				if ((value ?? value2).Enabled)
				{
					string text3 = ((value == null) ? "your" : "their");
					Add(r, Level.Mismatch, 1, text2, text, 0, text + " " + packageRec.Version + ": missing on " + text3 + " side", "[package] " + item + " " + packageRec.Version + ": missing on " + text3 + " side");
				}
			}
			else if (value.Enabled || value2.Enabled)
			{
				if (value.Enabled != value2.Enabled)
				{
					string text4 = (value.Enabled ? "their" : "your");
					Add(r, Level.Mismatch, 1, text2, text, 0, text + ": disabled on " + text4 + " side", "[package] " + item + ": disabled on " + text4 + " side (r2modman)");
				}
				else if (value.Version != value2.Version)
				{
					Add(r, Level.Mismatch, 1, text2, text, 1, text + ": you " + value.Version + ", them " + value2.Version, "[package] " + item + ": you " + value.Version + ", them " + value2.Version);
				}
			}
		}
	}

	private static Dictionary<string, PackageRec> PkgDict(List<PackageRec> list)
	{
		Dictionary<string, PackageRec> dictionary = new Dictionary<string, PackageRec>(StringComparer.OrdinalIgnoreCase);
		foreach (PackageRec item in list)
		{
			dictionary[item.Name] = item;
		}
		return dictionary;
	}

	internal static List<string> ConfigsToRequest(Manifest H, Manifest C, Rules rules)
	{
		Dictionary<string, CfgFileRec> dictionary = H.Configs.ToDictionary<CfgFileRec, string>((CfgFileRec c) => c.Path, StringComparer.OrdinalIgnoreCase);
		List<string> list = new List<string>();
		foreach (CfgFileRec config in C.Configs)
		{
			if (dictionary.TryGetValue(config.Path, out var value) && !(value.Hash == config.Hash) && rules.FileLevel(config.Path) != Level.Ignored)
			{
				list.Add(config.Path);
			}
		}
		return list;
	}

	private static void CompareConfigs(JoinReport r, JoinInput inp)
	{
		Manifest host = inp.Host;
		Manifest client = inp.Client;
		Rules rules = inp.Rules;
		Dictionary<string, CfgFileRec> dictionary = host.Configs.ToDictionary<CfgFileRec, string>((CfgFileRec c) => c.Path, StringComparer.OrdinalIgnoreCase);
		Dictionary<string, CfgFileRec> dictionary2 = client.Configs.ToDictionary<CfgFileRec, string>((CfgFileRec c) => c.Path, StringComparer.OrdinalIgnoreCase);
		int num = 0;
		foreach (string item in dictionary.Keys.Union<string>(dictionary2.Keys, StringComparer.OrdinalIgnoreCase).OrderBy<string, string>((string x) => x, StringComparer.OrdinalIgnoreCase))
		{
			dictionary.TryGetValue(item, out var value);
			dictionary2.TryGetValue(item, out var value2);
			Level level = rules.FileLevel(item);
			if (level == Level.Ignored)
			{
				r.IgnoredList.Add("config " + item);
				continue;
			}
			num++;
			string text = "cfg:" + item;
			string text2 = (rules.IsHostSyncedFile(item) ? " (host-synced: host's value applies)" : ((level == Level.Info) ? " (client-side setting)" : ""));
			if (value == null || value2 == null)
			{
				string text3 = ((value == null) ? "your" : "their");
				Add(r, level, 3, text, item, 0, item + ": missing on " + text3 + " side", "[config] " + item + ": missing on " + text3 + " side (mod not loaded yet there, or not installed)" + text2);
			}
			else if (!(value.Hash == value2.Hash))
			{
				inp.HostDetail.TryGetValue(item, out var value3);
				inp.ClientDetail.TryGetValue(item, out var value4);
				if (value3 == null || value4 == null)
				{
					string text4 = ((client.H("omitted:" + item) == "1") ? "details left out (over MaxDetailKB)" : (inp.DetailReceived ? "details missing" : "details not received"));
					Add(r, level, 3, text, item, 1, item + ": differs (" + text4 + ")", "[config] " + item + ": differs, " + text4 + text2);
				}
				else if (value3.Kind == "raw" || value4.Kind == "raw")
				{
					Add(r, level, 3, text, item, 1, item + ": content differs", "[config] " + item + ": content differs (not a BepInEx config; compare by hand)" + text2);
				}
				else
				{
					CompareKeys(r, item, value3, value4, rules);
				}
			}
		}
		r.ConfigCount = num;
	}

	private static void CompareKeys(JoinReport r, string path, CfgFile hf, CfgFile cf, Rules rules)
	{
		string text = "cfg:" + path;
		List<string> list = new List<string>();
		HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
		foreach (CfgEntry item in hf.Entries.Concat(cf.Entries))
		{
			if (hashSet.Add(item.Id))
			{
				list.Add(item.Id);
			}
		}
		Dictionary<string, CfgEntry> dictionary = ById(hf);
		Dictionary<string, CfgEntry> dictionary2 = ById(cf);
		foreach (string item2 in list)
		{
			dictionary.TryGetValue(item2, out var value);
			dictionary2.TryGetValue(item2, out var value2);
			CfgEntry cfgEntry = value ?? value2;
			string note;
			Level level = rules.KeyLevel(path, cfgEntry.Section, cfgEntry.Key, (value != null && value.ReadOnly) || (value2?.ReadOnly ?? false), out note);
			if (level == Level.Ignored)
			{
				if (value == null || value2 == null || !CfgParser.SameValue(value, value2))
				{
					r.IgnoredList.Add("key " + path + " [" + cfgEntry.Section + "] " + cfgEntry.Key + ((note != null) ? (" (" + note + ")") : ""));
				}
				continue;
			}
			string text2 = ShortSection(cfgEntry.Section) + "/" + cfgEntry.Key;
			if (value == null || value2 == null)
			{
				string text3 = ((value == null) ? "your" : "their");
				Add(r, level, 3, text, path, 20, text2 + " missing on " + text3 + " side", Util.Line2(path, "[" + cfgEntry.Section + "] " + cfgEntry.Key, (value == null) ? "(missing)" : value.Value, (value2 == null) ? "(missing)" : value2.Value, cfgEntry.Default ?? "", "key missing on " + text3 + " side" + ((note != null) ? ("; " + note) : "")));
			}
			else if (!CfgParser.SameValue(value, value2))
			{
				List<string> list2 = new List<string>();
				bool isDefault = value2.IsDefault;
				bool isDefault2 = value.IsDefault;
				if (isDefault && !isDefault2)
				{
					list2.Add("friend's value is the default, possibly reset on their side");
				}
				if (isDefault2 && !isDefault)
				{
					list2.Add("your value is the default");
				}
				if (value.Orphan || value2.Orphan)
				{
					list2.Add("orphaned on " + ((value.Orphan && value2.Orphan) ? "both sides" : (value.Orphan ? "your side" : "their side")));
				}
				if (note != null)
				{
					list2.Add(note);
				}
				Add(r, level, 3, text, path, 10, text2 + " " + Util.Plain(value.Value, 20) + " vs " + Util.Plain(value2.Value, 20), Util.Line2(path, "[" + value.Section + "] " + value.Key, value.Value, value2.Value, value.Default ?? value2.Default ?? "", string.Join("; ", list2.ToArray())));
			}
		}
	}

	private static Dictionary<string, CfgEntry> ById(CfgFile f)
	{
		Dictionary<string, CfgEntry> dictionary = new Dictionary<string, CfgEntry>(StringComparer.OrdinalIgnoreCase);
		foreach (CfgEntry entry in f.Entries)
		{
			if (!dictionary.ContainsKey(entry.Id))
			{
				dictionary[entry.Id] = entry;
			}
		}
		return dictionary;
	}

	private static string ShortSection(string s)
	{
		s = (s ?? "").Replace("\u200b", "").Trim();
		if (s.Length <= 24)
		{
			return s;
		}
		return s.Substring(0, 24);
	}
}
internal class LogWatch : ILogListener, IDisposable
{
	private static readonly List<string> Repairs = new List<string>();

	private static readonly object Lock = new object();

	private static LogWatch _instance;

	internal static int Count
	{
		get
		{
			lock (Lock)
			{
				return Repairs.Count;
			}
		}
	}

	internal static void Install()
	{
		if (_instance == null)
		{
			_instance = new LogWatch();
			Logger.Listeners.Add((ILogListener)(object)_instance);
		}
	}

	internal static List<string> Since(int index)
	{
		lock (Lock)
		{
			List<string> list = new List<string>();
			for (int i = Math.Max(0, index); i < Repairs.Count; i++)
			{
				list.Add(Repairs[i]);
			}
			return list;
		}
	}

	public void LogEvent(object sender, LogEventArgs e)
	{
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Invalid comparison between Unknown and I4
		try
		{
			if (e == null || (int)e.Level != 4 || e.Source == null || e.Source.SourceName != "NetSyncGuard")
			{
				return;
			}
			string text = ((e.Data != null) ? e.Data.ToString() : "");
			if (!text.StartsWith("Fixed an object that would have broken joining: ", StringComparison.Ordinal))
			{
				return;
			}
			lock (Lock)
			{
				if (Repairs.Count < 500)
				{
					Repairs.Add(DateTime.Now.ToString("HH:mm:ss") + " " + text.Substring("Fixed an object that would have broken joining: ".Length));
				}
			}
		}
		catch
		{
		}
	}

	public void Dispose()
	{
	}
}
internal class PluginRec
{
	public string Guid = "";

	public string Name = "";

	public string Version = "";

	public string Path = "";

	public string Hash = "";
}
internal class FileRec
{
	public string Path = "";

	public string Hash = "";

	public long Size;
}
internal class CfgFileRec
{
	public string Path = "";

	public string Hash = "";

	public string Kind = "bep";

	public int Keys;
}
internal class FolderRec
{
	public string Folder = "";

	public string Hash = "";

	public int Count;

	public long Bytes;
}
internal class Manifest
{
	public Dictionary<string, string> Header = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

	public Dictionary<string, string> Game = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

	public List<PluginRec> Plugins = new List<PluginRec>();

	public List<FileRec> Dlls = new List<FileRec>();

	public List<FileRec> OwnFiles = new List<FileRec>();

	public List<PackageRec> Packages = new List<PackageRec>();

	public List<FileRec> Assets = new List<FileRec>();

	public List<FolderRec> Listings = new List<FolderRec>();

	public List<CfgFileRec> Configs = new List<CfgFileRec>();

	public Dictionary<string, CfgFile> Details = new Dictionary<string, CfgFile>(StringComparer.OrdinalIgnoreCase);

	private CfgFile _cur;

	public bool HasModsYml => H("modsyml") == "1";

	public bool AnyPending
	{
		get
		{
			foreach (KeyValuePair<string, string> item in Game)
			{
				if (item.Value == "pending")
				{
					return true;
				}
			}
			foreach (PluginRec plugin in Plugins)
			{
				if (plugin.Hash == "pending")
				{
					return true;
				}
			}
			foreach (FileRec dll in Dlls)
			{
				if (dll.Hash == "pending")
				{
					return true;
				}
			}
			return false;
		}
	}

	public string H(string key)
	{
		if (!Header.TryGetValue(key, out var value))
		{
			return "";
		}
		return value;
	}

	public string G(string key)
	{
		if (!Game.TryGetValue(key, out var value))
		{
			return "";
		}
		return value;
	}

	public List<PackageRec> PackagesFrom(string source)
	{
		List<PackageRec> list = new List<PackageRec>();
		foreach (PackageRec package in Packages)
		{
			if (package.Source == source)
			{
				list.Add(package);
			}
		}
		return list;
	}

	public string Serialize(bool includeDetails)
	{
		StringBuilder stringBuilder = new StringBuilder(32768);
		foreach (KeyValuePair<string, string> item in Header)
		{
			stringBuilder.Append(Util.Line("H", item.Key, item.Value)).Append('\n');
		}
		foreach (KeyValuePair<string, string> item2 in Game)
		{
			stringBuilder.Append(Util.Line("G", item2.Key, item2.Value)).Append('\n');
		}
		foreach (PluginRec plugin in Plugins)
		{
			stringBuilder.Append(Util.Line("P", plugin.Guid, plugin.Name, plugin.Version, plugin.Path, plugin.Hash)).Append('\n');
		}
		foreach (FileRec dll in Dlls)
		{
			stringBuilder.Append(Util.Line("D", dll.Path, dll.Size.ToString(CultureInfo.InvariantCulture), dll.Hash)).Append('\n');
		}
		foreach (FileRec ownFile in OwnFiles)
		{
			stringBuilder.Append(Util.Line("E", ownFile.Path, ownFile.Size.ToString(CultureInfo.InvariantCulture), ownFile.Hash)).Append('\n');
		}
		foreach (FileRec asset in Assets)
		{
			stringBuilder.Append(Util.Line("A", asset.Path, asset.Size.ToString(CultureInfo.InvariantCulture))).Append('\n');
		}
		foreach (FolderRec listing in Listings)
		{
			stringBuilder.Append(Util.Line("L", listing.Folder, listing.Hash, listing.Count.ToString(CultureInfo.InvariantCulture), listing.Bytes.ToString(CultureInfo.InvariantCulture))).Append('\n');
		}
		foreach (PackageRec package in Packages)
		{
			stringBuilder.Append(Util.Line("K", package.Name, package.Version, package.Enabled ? "1" : "0", package.Source, package.Display)).Append('\n');
		}
		foreach (CfgFileRec config in Configs)
		{
			stringBuilder.Append(Util.Line("C", config.Path, config.Hash, config.Keys.ToString(CultureInfo.InvariantCulture), config.Kind)).Append('\n');
		}
		if (includeDetails)
		{
			foreach (CfgFile value in Details.Values)
			{
				AppendDetail(stringBuilder, value);
			}
		}
		return stringBuilder.ToString();
	}

	internal static void AppendDetail(StringBuilder sb, CfgFile f)
	{
		sb.Append(Util.Line("F", f.Path, f.Kind, f.Hash, f.OwnerGuid ?? "", f.OwnerName ?? "", f.OwnerVersion ?? "")).Append('\n');
		foreach (CfgEntry entry in f.Entries)
		{
			bool flag = entry.HasDefault && entry.Default == entry.Value;
			string text = (entry.Orphan ? "o" : "") + (entry.ReadOnly ? "r" : "") + (entry.HasDefault ? (flag ? "=" : "d") : "");
			sb.Append(Util.Line("V", entry.Section, entry.Key, entry.Value, flag ? "" : (entry.Default ?? ""), entry.Type ?? "", text)).Append('\n');
		}
	}

	internal static string BuildDetail(IEnumerable<CfgFile> files, int capBytes, out List<string> omitted)
	{
		StringBuilder stringBuilder = new StringBuilder();
		omitted = new List<string>();
		List<CfgFile> list = new List<CfgFile>(files);
		foreach (CfgFile item in list)
		{
			StringBuilder stringBuilder2 = new StringBuilder();
			AppendDetail(stringBuilder2, item);
			if (stringBuilder.Length + stringBuilder2.Length > capBytes - 80 * (list.Count + 1))
			{
				omitted.Add(item.Path);
			}
			else
			{
				stringBuilder.Append(stringBuilder2);
			}
		}
		if (omitted.Count > 0)
		{
			stringBuilder.Append(Util.Line("T", omitted.Count.ToString(CultureInfo.InvariantCulture))).Append('\n');
			foreach (string item2 in omitted)
			{
				stringBuilder.Append(Util.Line("X", item2)).Append('\n');
			}
		}
		return stringBuilder.ToString();
	}

	internal static string DetailText(IEnumerable<CfgFile> files)
	{
		StringBuilder stringBuilder = new StringBuilder();
		foreach (CfgFile file in files)
		{
			AppendDetail(stringBuilder, file);
		}
		return stringBuilder.ToString();
	}

	public static Manifest Parse(string text)
	{
		Manifest manifest = new Manifest();
		if (string.IsNullOrEmpty(text))
		{
			return manifest;
		}
		string[] array = text.Split('\n');
		for (int i = 0; i < array.Length; i++)
		{
			string text2 = array[i].TrimEnd('\r');
			if (text2.Length != 0)
			{
				string[] f = Util.Fields(text2);
				try
				{
					manifest.ParseRecord(f);
				}
				catch
				{
				}
			}
		}
		return manifest;
	}

	internal void ParseRecord(string[] f)
	{
		string text = f[0];
		if (text == null)
		{
			return;
		}
		int length = text.Length;
		if (length != 1)
		{
			return;
		}
		long result;
		switch (text[0])
		{
		case 'H':
			Header[Util.F(f, 1)] = Util.F(f, 2);
			break;
		case 'G':
			Game[Util.F(f, 1)] = Util.F(f, 2);
			break;
		case 'P':
			Plugins.Add(new PluginRec
			{
				Guid = Util.F(f, 1),
				Name = Util.F(f, 2),
				Version = Util.F(f, 3),
				Path = Util.F(f, 4),
				Hash = Util.F(f, 5)
			});
			break;
		case 'D':
		case 'E':
			long.TryParse(Util.F(f, 2), NumberStyles.Integer, CultureInfo.InvariantCulture, out result);
			((f[0] == "D") ? Dlls : OwnFiles).Add(new FileRec
			{
				Path = Util.F(f, 1),
				Size = result,
				Hash = Util.F(f, 3)
			});
			break;
		case 'A':
			long.TryParse(Util.F(f, 2), NumberStyles.Integer, CultureInfo.InvariantCulture, out result);
			Assets.Add(new FileRec
			{
				Path = Util.F(f, 1),
				Size = result,
				Hash = "-"
			});
			break;
		case 'L':
		{
			int.TryParse(Util.F(f, 3), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2);
			long.TryParse(Util.F(f, 4), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result3);
			Listings.Add(new FolderRec
			{
				Folder = Util.F(f, 1),
				Hash = Util.F(f, 2),
				Count = result2,
				Bytes = result3
			});
			break;
		}
		case 'K':
			Packages.Add(new PackageRec
			{
				Name = Util.F(f, 1),
				Version = Util.F(f, 2),
				Enabled = (Util.F(f, 3) != "0"),
				Source = Util.F(f, 4),
				Display = Util.F(f, 5)
			});
			break;
		case 'C':
		{
			int.TryParse(Util.F(f, 3), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result4);
			Configs.Add(new CfgFileRec
			{
				Path = Util.F(f, 1),
				Hash = Util.F(f, 2),
				Keys = result4,
				Kind = ((Util.F(f, 4) == "") ? "bep" : Util.F(f, 4))
			});
			break;
		}
		case 'F':
		{
			CfgFile cfgFile = new CfgFile
			{
				Path = Util.F(f, 1),
				Kind = Util.F(f, 2),
				Hash = Util.F(f, 3)
			};
			cfgFile.OwnerGuid = NullIfEmpty(Util.F(f, 4));
			cfgFile.OwnerName = NullIfEmpty(Util.F(f, 5));
			cfgFile.OwnerVersion = NullIfEmpty(Util.F(f, 6));
			Details[cfgFile.Path] = cfgFile;
			_cur = cfgFile;
			break;
		}
		case 'V':
			if (_cur != null)
			{
				string text2 = Util.F(f, 6);
				string text3 = Util.F(f, 3);
				_cur.Entries.Add(new CfgEntry
				{
					Section = Util.F(f, 1),
					Key = Util.F(f, 2),
					Value = text3,
					Default = ((text2.IndexOf('=') >= 0) ? text3 : ((text2.IndexOf('d') >= 0) ? Util.F(f, 4) : null)),
					Type = NullIfEmpty(Util.F(f, 5)),
					Orphan = (text2.IndexOf('o') >= 0),
					ReadOnly = (text2.IndexOf('r') >= 0)
				});
			}
			break;
		case 'T':
			Header["truncated"] = Util.F(f, 1);
			break;
		case 'X':
			Header["omitted:" + Util.F(f, 1)] = "1";
			break;
		case 'B':
		case 'I':
		case 'J':
		case 'M':
		case 'N':
		case 'O':
		case 'Q':
		case 'R':
		case 'S':
		case 'U':
		case 'W':
			break;
		}
	}

	private static string NullIfEmpty(string s)
	{
		if (!string.IsNullOrEmpty(s))
		{
			return s;
		}
		return null;
	}

	internal static string PluginFolder(string relPath)
	{
		if (string.IsNullOrEmpty(relPath))
		{
			return null;
		}
		string text = relPath.Replace('\\', '/');
		if (!text.StartsWith("plugins/", StringComparison.OrdinalIgnoreCase))
		{
			return null;
		}
		text = text.Substring(8);
		int num = text.IndexOf('/');
		if (num <= 0)
		{
			return null;
		}
		return text.Substring(0, num);
	}
}
internal static class Net
{
	internal class Stage0Info
	{
		public float Time;

		public bool SteamMode;

		public bool HasPc;

		public string Fingerprint = "";

		public string SteamId = "";

		public string Result = "";

		public int NsgIndex;

		public bool Approved = true;

		public string Reason = "";
	}

	internal enum HState
	{
		WaitingHello,
		Processing,
		WaitingDetail,
		Done,
		TimedOut
	}

	internal class HostSession
	{
		public ulong ClientId;

		public uint SessionId;

		public HState State;

		public float ConnectedAt;

		public float HelloAt;

		public float RequestAt;

		public Stage0Info Stage0;

		public int NsgIndex;

		public bool NoPackCheck;

		public bool Announced;

		public bool WantsVerdict;

		public bool Reported;

		public Manifest Client;

		public Manifest Host;

		public List<CfgFile> HostConfigs;

		public long BytesIn;

		public long BytesOut;

		public int Requested;
	}

	private struct Outgoing
	{
		public string Name;

		public ulong Target;

		public byte[] Data;
	}

	[Serializable]
	[CompilerGenerated]
	private sealed class <>c
	{
		public static readonly <>c <>9 = new <>c();

		public static HandleNamedMessageDelegate <>9__24_0;

		public static HandleNamedMessageDelegate <>9__24_1;

		public static HandleNamedMessageDelegate <>9__24_2;

		public static HandleNamedMessageDelegate <>9__24_3;

		public static Func<string, bool> <>9__36_0;

		public static Func<string, string> <>9__36_1;

		public static Func<DiffItem, bool> <>9__38_0;

		public static Func<string, string> <>9__50_0;

		internal void <EnsureRegistered>b__24_0(ulong s, FastBufferReader r)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Receive(1, s, r);
		}

		internal void <EnsureRegistered>b__24_1(ulong s, FastBufferReader r)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Receive(2, s, r);
		}

		internal void <EnsureRegistered>b__24_2(ulong s, FastBufferReader r)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Receive(3, s, r);
		}

		internal void <EnsureRegistered>b__24_3(ulong s, FastBufferReader r)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Receive(4, s, r);
		}

		internal bool <OnVerdict>b__36_0(string l)
		{
			return l.Trim().Length > 0;
		}

		internal string <OnVerdict>b__36_1(string l)
		{
			return "Host's check: " + l;
		}

		internal bool <ShowReport>b__38_0(DiffItem i)
		{
			return i.Level == Level.Mismatch;
		}

		internal string <RepeatOrRerun>b__50_0(string l)
		{
			return "Host's check: " + l;
		}
	}

	internal const string HelloMsg = "jacob.packcheck.hello";

	internal const string RequestMsg = "jacob.packcheck.request";

	internal const string DetailMsg = "jacob.packcheck.detail";

	internal const string VerdictMsg = "jacob.packcheck.verdict";

	private const float DetailTimeout = 30f;

	private static CustomMessagingManager _registeredOn;

	private static NetworkManager _hookedNm;

	private static readonly Reassembler Re = new Reassembler();

	private static readonly Random Rng = new Random();

	private static bool _loggedDrop;

	private static bool _loggedSendError;

	private static readonly Dictionary<ulong, Stage0Info> Stage0 = new Dictionary<ulong, Stage0Info>();

	private static readonly Dictionary<ulong, HostSession> Hosted = new Dictionary<ulong, HostSession>();

	private static uint _clientSession;

	private static float _joinedAt = -1f;

	private static bool _helloSent;

	internal static string[] LastVerdict;

	internal static JoinReport LastReport;

	internal static ulong LastReportClient;

	private static readonly Queue<Outgoing> Out = new Queue<Outgoing>();

	internal static void EnsureRegistered(NetworkManager nm)
	{
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Expected O, but got Unknown
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Expected O, but got Unknown
		//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: Expected O, but got Unknown
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_012b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0131: Expected O, but got Unknown
		if ((Object)(object)_hookedNm != (Object)(object)nm)
		{
			if ((Object)(object)_hookedNm != (Object)null)
			{
				try
				{
					_hookedNm.OnClientConnectedCallback -= OnClientConnected;
					_hookedNm.OnClientDisconnectCallback -= OnClientDisconnect;
				}
				catch
				{
				}
			}
			_hookedNm = nm;
			nm.OnClientConnectedCallback += OnClientConnected;
			nm.OnClientDisconnectCallback += OnClientDisconnect;
		}
		CustomMessagingManager customMessagingManager = nm.CustomMessagingManager;
		if (customMessagingManager == null || customMessagingManager == _registeredOn)
		{
			return;
		}
		_registeredOn = customMessagingManager;
		object obj2 = <>c.<>9__24_0;
		if (obj2 == null)
		{
			HandleNamedMessageDelegate val = delegate(ulong s, FastBufferReader r)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				Receive(1, s, r);
			};
			<>c.<>9__24_0 = val;
			obj2 = (object)val;
		}
		customMessagingManager.RegisterNamedMessageHandler("jacob.packcheck.hello", (HandleNamedMessageDelegate)obj2);
		object obj3 = <>c.<>9__24_1;
		if (obj3 == null)
		{
			HandleNamedMessageDelegate val2 = delegate(ulong s, FastBufferReader r)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				Receive(2, s, r);
			};
			<>c.<>9__24_1 = val2;
			obj3 = (object)val2;
		}
		customMessagingManager.RegisterNamedMessageHandler("jacob.packcheck.request", (HandleNamedMessageDelegate)obj3);
		object obj4 = <>c.<>9__24_2;
		if (obj4 == null)
		{
			HandleNamedMessageDelegate val3 = delegate(ulong s, FastBufferReader r)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				Receive(3, s, r);
			};
			<>c.<>9__24_2 = val3;
			obj4 = (object)val3;
		}
		customMessagingManager.RegisterNamedMessageHandler("jacob.packcheck.detail", (HandleNamedMessageDelegate)obj4);
		object obj5 = <>c.<>9__24_3;
		if (obj5 == null)
		{
			HandleNamedMessageDelegate val4 = delegate(ulong s, FastBufferReader r)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				Receive(4, s, r);
			};
			<>c.<>9__24_3 = val4;
			obj5 = (object)val4;
		}
		customMessagingManager.RegisterNamedMessageHandler("jacob.packcheck.verdict", (HandleNamedMessageDelegate