Decompiled source of BashTerm v0.2.1

BashTerm.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using LevelGeneration;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("BashTerm")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+f67370157283493da87410b934eae6f91a0a9f05")]
[assembly: AssemblyProduct("BashTerm")]
[assembly: AssemblyTitle("BashTerm")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace BashTerm
{
	internal static class ConfigMaster
	{
		public static ConfigFile conf;

		public static ConfigEntry<bool> _EnableRVAlias;

		public static ConfigEntry<bool> _EnableUVAlias;

		public static ConfigEntry<bool> _LsObjExpansions;

		public static ConfigEntry<bool> _LsConvertsNum2ZoneId;

		public static ConfigEntry<string> CustomCmdAliases;

		public static ConfigEntry<string> CustomObjExpansions;

		public static ConfigEntry<bool> _DEBUG;

		public static Dictionary<string, string> CmdExpExact;

		public static List<(string Prefix, string Expansion)> CmdExpPrefix;

		public static Dictionary<string, string> ObjExpExact;

		public static List<(string Prefix, string Expansion)> ObjExpPrefix;

		public static bool EnableRVAlias => _EnableRVAlias.Value;

		public static bool EnableUVAlias => _EnableUVAlias.Value;

		public static bool DEBUG => _DEBUG.Value;

		public static bool LsObjExpansions => _LsObjExpansions.Value;

		public static bool LsConvertsNum2ZoneId => _LsConvertsNum2ZoneId.Value;

		static ConfigMaster()
		{
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c2: Expected O, but got Unknown
			CmdExpExact = new Dictionary<string, string>
			{
				{ "ls", "list" },
				{ "l", "list" },
				{ "lsu", "list u" },
				{ "lu", "list u" },
				{ "uc", "uplink_connect" },
				{ "uv", "uplink_verify" },
				{ "rs", "reactor_startup" },
				{ "start", "reactor_startup" },
				{ "rsd", "reactor_shutdown" },
				{ "shut", "reactor_shutdown" },
				{ "shutdown", "reactor_shutdown" },
				{ "rv", "reactor_verify" },
				{ "cat", "read" },
				{ "p", "ping" },
				{ "q", "query" },
				{ "clear", "cls" },
				{ "r", "raw" }
			};
			CmdExpPrefix = new List<(string, string)>();
			ObjExpExact = new Dictionary<string, string>
			{
				{ "nhsu", "neonate_hsu" },
				{ "diss", "disinfection_station" }
			};
			ObjExpPrefix = new List<(string, string)>
			{
				("med", "medipack"),
				("to", "tool_refill"),
				("am", "ammopack"),
				("dis", "disinfect_pack"),
				("turb", "fog_turbine"),
				("bk", "bulkhead_key"),
				("bulk", "bulkhead_key"),
				("bd", "bulkhead_dc"),
				("his", "hisec_cargo"),
				("dc", "data_cube"),
				("data", "data_cube"),
				("lock", "locker"),
				("sec", "sec_door"),
				("sd", "sec_door"),
				("nfr", "nframe"),
				("gen", "generator")
			};
			conf = new ConfigFile(Path.Combine(Paths.ConfigPath, "BashTerm.cfg"), true);
			int num = 1;
			string text = $"({num++}) Aliases";
			_EnableRVAlias = conf.Bind<bool>(text, "Enable REACTOR_VERIFY Alias", true, "By Default Maps \"RV\" to \"REACTOR_VERIFY\"");
			_EnableUVAlias = conf.Bind<bool>(text, "Enable UPLINK_VERIFY Alias", true, "By Default Maps \"UV\" to \"UPLINK_VERIFY\"");
			text = $"({num++}) Advanced Aliases / Expansions";
			_LsObjExpansions = conf.Bind<bool>(text, "LS Performs Object Name Expansion", false, "Attempts to expand first non-number argument for LS (e.g. LIST TOOL TOOL to LIST TOOL_REFILL TOOL)");
			_LsConvertsNum2ZoneId = conf.Bind<bool>(text, "LS Converts Number to Zone ID", false, "Converts first integer argument for LS to zone identifier (e.g. LS 49 50 to LS E_49 50)");
			CustomCmdAliases = conf.Bind<string>(text, "Custom Command Aliases", "", "Add custom command aliases here.\nMust match Format: \"<command expression>,<alias1>,<alias2>:<command>,<alias1>\"\nPrefix Match: \"Pre+\", Exact Match: \"Exact\"e.g. \"list u, lsu, lu: uplink_verify, uv+\"\nNote: Terms are case-insensitive. Newer definitions override older ones, including defaults. Check README on GitHub/GitLab for details.");
			CustomObjExpansions = conf.Bind<string>(text, "Custom Object Name Expansions", "", "Add custom object name expansions here.\nMust match Format: \"<expansion1>,<identifier1>,<identifier2>:<expansion2>,<identifier1>\"\nPrefix Match: \"Pre+\", Exact Match: \"Exact\"e.g. \"get the fk out, gtfo, gtfi: my_custom_object, mco+\"\nNote: Terms are case-insensitive. Newer definitions override older ones, including defaults. Check README on GitHub/GitLab for details.");
			text = "(Z) Dev";
			_DEBUG = conf.Bind<bool>(text, "Enable Debugging", false, "Enables Debug Logging");
		}

		public static void Init()
		{
			int expansionCount = GetExpansionCount();
			int num = 0;
			num += LoadExpansionPairs(CustomCmdAliases.Value, ref CmdExpExact, ref CmdExpPrefix);
			num += LoadExpansionPairs(CustomObjExpansions.Value, ref ObjExpExact, ref ObjExpPrefix);
			int expansionCount2 = GetExpansionCount();
			Logger.Info($"Aliases/Expansions Loaded: {expansionCount} Default ({num} Prefix Overrides) + {expansionCount2 - expansionCount} User = {expansionCount2} Total");
			Logger.Info("Config is Loaded");
		}

		public static int GetExpansionCount()
		{
			return CmdExpExact.Count + CmdExpPrefix.Count + ObjExpExact.Count + ObjExpPrefix.Count;
		}

		public static int LoadExpansionPairs(string source, ref Dictionary<string, string> targetExact, ref List<(string Prefix, string Expansion)> targetPrefix)
		{
			List<List<string>> list = ParseUtil.FromUserDefGroups(source);
			int num = 0;
			foreach (List<string> item in list)
			{
				string text = item[0];
				if (item.Count < 2 || string.IsNullOrWhiteSpace(text))
				{
					continue;
				}
				for (int i = 1; i < item.Count; i++)
				{
					string term = item[i];
					if (string.IsNullOrWhiteSpace(term))
					{
						continue;
					}
					if (term.EndsWith("+"))
					{
						term = term.Substring(0, term.Length - 1);
						int num2 = targetPrefix.FindIndex(((string Prefix, string Expansion) x) => x.Prefix == term);
						if (num2 != -1)
						{
							targetPrefix[num2] = (term, text);
							num++;
							Logger.Debug("Overwriting Prefix Expansion: (" + term + " -> " + text + ")");
						}
						else
						{
							targetPrefix.Add((term, text));
						}
					}
					else
					{
						targetExact[term] = text;
					}
				}
			}
			targetPrefix.Sort(((string Prefix, string Expansion) a, (string Prefix, string Expansion) b) => b.Prefix.Length.CompareTo(a.Prefix.Length));
			return num;
		}
	}
	internal static class GameContext
	{
	}
	internal static class Logger
	{
		private static ManualLogSource m_LogSource;

		public static void SetupFromInit(ManualLogSource logSource)
		{
			m_LogSource = logSource;
		}

		private static string Format(object data)
		{
			return data.ToString();
		}

		public static void Debug(object msg)
		{
			if (ConfigMaster.DEBUG)
			{
				m_LogSource.LogInfo((object)Format(msg));
			}
		}

		public static void Info(object msg)
		{
			m_LogSource.LogInfo((object)Format(msg));
		}

		public static void Warn(object msg)
		{
			m_LogSource.LogWarning((object)Format(msg));
		}

		public static void Error(object msg)
		{
			m_LogSource.LogError((object)Format(msg));
		}

		public static void Fatal(object msg)
		{
			m_LogSource.LogFatal((object)Format(msg));
		}
	}
	internal static class ParseUtil
	{
		private static readonly Dictionary<string, TermCmd> _Txt2Cmd = new Dictionary<string, TermCmd>
		{
			{
				"",
				TermCmd.None
			},
			{
				"help",
				TermCmd.Help
			},
			{
				"commands",
				TermCmd.Commands
			},
			{
				"cls",
				TermCmd.Cls
			},
			{
				"exit",
				TermCmd.Exit
			},
			{
				"override_lockdown",
				TermCmd.Override
			},
			{
				"deactivate_alarms",
				TermCmd.DisableAlarm
			},
			{
				"activate_beacon",
				TermCmd.ActivateBeacon
			},
			{
				"list",
				TermCmd.ShowList
			},
			{
				"query",
				TermCmd.Query
			},
			{
				"ping",
				TermCmd.Ping
			},
			{
				"reactor_startup",
				TermCmd.ReactorStartup
			},
			{
				"reactor_verify",
				TermCmd.ReactorVerify
			},
			{
				"reactor_shutdown",
				TermCmd.ReactorShutdown
			},
			{
				"uplink_connect",
				TermCmd.TerminalUplinkConnect
			},
			{
				"uplink_verify",
				TermCmd.TerminalUplinkVerify
			},
			{
				"uplink_confirm",
				TermCmd.TerminalUplinkConfirm
			},
			{
				"logs",
				TermCmd.ListLogs
			},
			{
				"read",
				TermCmd.ReadLog
			},
			{
				"info",
				TermCmd.Info
			},
			{
				"raw",
				TermCmd.Raw
			}
		};

		public static TermCmd GetCmdType(string input)
		{
			input = input.Split(' ')[0].Trim().ToLower();
			if (!_Txt2Cmd.TryGetValue(input, out var value))
			{
				return TermCmd.None;
			}
			return value;
		}

		public static string GetCmdExpansion(string input)
		{
			if (string.IsNullOrWhiteSpace(input))
			{
				return "";
			}
			if (ConfigMaster.CmdExpExact.TryGetValue(input, out string value))
			{
				return value;
			}
			foreach (var item in ConfigMaster.CmdExpPrefix)
			{
				if (input.StartsWith(item.Prefix))
				{
					return item.Expansion;
				}
			}
			return input;
		}

		public static string GetObjExpansion(string input)
		{
			if (string.IsNullOrWhiteSpace(input))
			{
				return "";
			}
			if (ConfigMaster.ObjExpExact.TryGetValue(input, out string value))
			{
				return value;
			}
			foreach (var item in ConfigMaster.ObjExpPrefix)
			{
				if (input.StartsWith(item.Prefix))
				{
					return item.Expansion;
				}
			}
			return input;
		}

		public static List<List<string>> FromUserDefGroups(string input)
		{
			input = input.ToLower();
			StringBuilder stringBuilder = new StringBuilder();
			List<List<string>> list = new List<List<string>>();
			List<string> list2 = new List<string>();
			bool flag = false;
			string text = input;
			foreach (char c in text)
			{
				if (flag)
				{
					stringBuilder.Append(c);
					flag = false;
					continue;
				}
				switch (c)
				{
				case '\\':
					flag = true;
					break;
				case ',':
					list2.Add(stringBuilder.ToString().Trim());
					stringBuilder.Clear();
					break;
				case ':':
					list2.Add(stringBuilder.ToString().Trim());
					list.Add(list2);
					list2 = new List<string>();
					stringBuilder.Clear();
					break;
				default:
					stringBuilder.Append(c);
					break;
				}
			}
			list2.Add(stringBuilder.ToString().Trim());
			list.Add(list2);
			return list;
		}

		public static string[] CleanSplit(string input)
		{
			return (from s in input.Split(' ')
				select s.Trim()).ToArray();
		}

		public static string[] CleanSplit(char delimiter, string input)
		{
			return (from s in input.Split(delimiter)
				select s.Trim()).ToArray();
		}
	}
	[HarmonyPatch]
	internal class Patch
	{
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "EvaluateInput")]
		[HarmonyPrefix]
		public static void PreEvaluateCmd(ref string inputString)
		{
			string[] array = ParseUtil.CleanSplit(inputString.ToLower());
			string text = "";
			string text2 = "";
			Logger.Debug("Pre-Evaluate Command Received = \"" + inputString + "\"");
			if (array.Length == 0)
			{
				return;
			}
			string text3 = array[0];
			if (array.Length > 1)
			{
				text = array[1];
			}
			if (array.Length > 2)
			{
				text2 = array[2];
			}
			string cmdExpansion = ParseUtil.GetCmdExpansion(text3);
			TermCmd cmdType = ParseUtil.GetCmdType(cmdExpansion);
			Logger.Debug("PreEval: cmdExpression = " + cmdExpansion);
			Logger.Debug("PreEval: cmdType = " + cmdType.ToString("G"));
			bool flag = true;
			switch (cmdType)
			{
			case TermCmd.ShowList:
			{
				if (ParseUtil.GetCmdExpansion("lsu") == cmdExpansion)
				{
					if (Util.IsInt(text))
					{
						text = "e_" + text;
					}
					break;
				}
				bool flag2 = Util.IsInt(text);
				bool flag3 = Util.IsInt(text2);
				if (ConfigMaster.LsConvertsNum2ZoneId)
				{
					if (flag2)
					{
						text = "e_" + text;
					}
					else if (flag3)
					{
						text2 = "e_" + text2;
					}
				}
				if (ConfigMaster.LsObjExpansions)
				{
					if (!string.IsNullOrWhiteSpace(text) && !flag2)
					{
						text = ParseUtil.GetObjExpansion(text);
					}
					else if (!string.IsNullOrWhiteSpace(text2) && !flag3)
					{
						text2 = ParseUtil.GetObjExpansion(text2);
					}
				}
				break;
			}
			case TermCmd.TerminalUplinkVerify:
				flag = ConfigMaster.EnableUVAlias;
				break;
			case TermCmd.ReactorVerify:
				flag = ConfigMaster.EnableRVAlias;
				break;
			case TermCmd.Ping:
				if (array.Length > 3 || (array.Length == 3 && !Util.ContainsFlag(array)))
				{
					text = ParseUtil.GetObjExpansion(array[1]) + "_" + Util.Concat('_', array, 2, array.Length);
					text2 = "";
				}
				break;
			case TermCmd.Query:
				if (array.Length > 2)
				{
					text = ParseUtil.GetObjExpansion(array[1]) + "_" + Util.Concat('_', array, 2, array.Length);
					text2 = "";
				}
				break;
			case TermCmd.Raw:
				inputString = Util.Concat(array, 1, array.Length);
				inputString = inputString.ToUpper().Trim();
				return;
			}
			if (flag)
			{
				Logger.Debug("Doing Expansion");
				text3 = cmdExpansion;
			}
			Logger.Debug("cmd = " + text3);
			Logger.Debug("param1 = " + text);
			Logger.Debug("param2 = " + text2);
			inputString = Util.Concat(text3, text, text2);
			inputString = inputString.ToUpper().Trim();
			Logger.Debug("Command Evaluated as \"" + inputString + "\"");
		}
	}
	[BepInPlugin("io.takina.gtfo.BashTerm", "BashTerm", "0.2.1")]
	public class Plugin : BasePlugin
	{
		public const string NAME = "BashTerm";

		public const string GUID = "io.takina.gtfo.BashTerm";

		public const string VERSION = "0.2.1";

		public override void Load()
		{
			Logger.SetupFromInit(((BasePlugin)this).Log);
			Logger.Info("BashTerm io.takina.gtfo.BashTerm 0.2.1");
			Logger.Info("Patching...");
			Harmony.CreateAndPatchAll(typeof(Patch), "io.takina.gtfo.BashTerm");
			ConfigMaster.Init();
			Logger.Info("Finished Patching");
		}
	}
	public enum TermCmd : byte
	{
		None,
		Help,
		Commands,
		Cls,
		Exit,
		Open,
		Close,
		Activate,
		Deactivate,
		EmptyLine,
		InvalidCommand,
		DownloadData,
		ViewSecurityLog,
		Override,
		DisableAlarm,
		Locate,
		ActivateBeacon,
		Find,
		ShowList,
		Query,
		Ping,
		ReactorStartup,
		ReactorVerify,
		ReactorShutdown,
		WardenObjectiveSpecialCommand,
		TerminalUplinkConnect,
		TerminalUplinkVerify,
		TerminalUplinkConfirm,
		ListLogs,
		ReadLog,
		TryUnlockingTerminal,
		WardenObjectiveGatherCommand,
		TerminalCorruptedUplinkConnect,
		TerminalCorruptedUplinkVerify,
		UsedCommand,
		UniqueCommand1,
		UniqueCommand2,
		UniqueCommand3,
		UniqueCommand4,
		UniqueCommand5,
		Info,
		Raw
	}
	internal static class Util
	{
		public static string Concat(params string[] args)
		{
			return Concat(' ', args);
		}

		public static string Concat(char delimiter, params string[] args)
		{
			return Concat(delimiter, args, 0, args.Length);
		}

		public static string Concat(string[] args, int start, int end)
		{
			return Concat(' ', args, start, end);
		}

		public static string Concat(char delimiter, string[] args, int start, int end)
		{
			if (start < 0)
			{
				start = 0;
			}
			if (end > args.Length)
			{
				end = args.Length;
			}
			if (args.Length == 0 || start >= end)
			{
				return "";
			}
			string text = args[start];
			for (int i = start + 1; i < end; i++)
			{
				text = text + delimiter + args[i];
			}
			return text;
		}

		public static bool ContainsFlag(params string[] args)
		{
			for (int i = 0; i < args.Length; i++)
			{
				if (args[i].StartsWith("-"))
				{
					return true;
				}
			}
			return false;
		}

		public static bool IsInt(string input)
		{
			int result;
			return int.TryParse(input, out result);
		}

		public static void printMaps()
		{
			Logger.Info("CmdExpExact:");
			foreach (KeyValuePair<string, string> item in ConfigMaster.CmdExpExact)
			{
				Logger.Info("\t" + item.Key + " -> " + item.Value);
			}
			Logger.Info("CmdExpPrefix:");
			foreach (var item2 in ConfigMaster.CmdExpPrefix)
			{
				Logger.Info("\t" + item2.Prefix + "+ -> " + item2.Expansion);
			}
			Logger.Info("ObjExpExact:");
			foreach (KeyValuePair<string, string> item3 in ConfigMaster.ObjExpExact)
			{
				Logger.Info("\t" + item3.Key + " -> " + item3.Value);
			}
			Logger.Info("ObjExpPrefix:");
			foreach (var item4 in ConfigMaster.ObjExpPrefix)
			{
				Logger.Info("\t" + item4.Prefix + "+ -> " + item4.Expansion);
			}
		}
	}
}