using Fiddler;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading;

namespace AntiAntiAddiction
{
    class Program
    {

        //p/invoke
        static ConsoleEventDelegate handler;
        private delegate bool ConsoleEventDelegate(int eventType);
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

        static Process proxifier;
        static bool hacked = false;

        public static bool UninstallCertificate()
        {

            X509Store certStore = new X509Store(StoreName.Root,
                                                StoreLocation.LocalMachine);
            certStore.Open(OpenFlags.ReadWrite);

            try
            {
                certStore.Remove(CertMaker.GetRootCertificate());
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                certStore.Close();
            }
            return true;
        }
        public static bool InstallCertificate()
        {

            if (!CertMaker.createRootCert())
                return false;

            X509Store certStore = new X509Store(StoreName.Root,
                                                StoreLocation.LocalMachine);
            certStore.Open(OpenFlags.ReadWrite);

            try
            {
                certStore.Add(CertMaker.GetRootCertificate());
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                certStore.Close();
            }
            return true;
        }
        static void startWpfLauncher()
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Process wpflauncher = new Process();
            string ProgramFiles = Environment.GetEnvironmentVariable("ProgramFiles");
            String fullPath = Path.Combine(ProgramFiles, "Netease", "MCLauncher", "WPFLauncher.exe");

            if (File.Exists(fullPath))
            {
                Console.Write("Starting " + fullPath + "... ");
                wpflauncher.StartInfo.FileName = fullPath;
                wpflauncher.Start();

                while (wpflauncher.MainWindowHandle == (IntPtr)0) { };
                Console.WriteLine("Started!");


            }
            else
            {
                Console.WriteLine("- Cannot find MC China WPFLauncher.exe");
                while (true) { };
            }
        }

        static bool ConsoleEventCallback(int eventType)
        {
            if (eventType == 2)
            {
                UninstallCertificate();

                File.WriteAllBytes(@"ppe\Profiles\Default.ppx", Properties.Resources.ProxyNo);                
                proxifier.Kill();
                FiddlerApplication.Shutdown();

            }
            return false;
        }

        static void Main(string[] args)
        {
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Dear China, Gaming Addiction Does NOT Exist!");
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine("-- HACKING MINECRAFT CHINA --");

            foreach (Process proc in Process.GetProcessesByName("Proxifier"))
            {
                proc.Kill();
            }

            foreach (Process proc in Process.GetProcessesByName("WPFLauncher"))
            {
                proc.Kill();
            }

            File.WriteAllBytes(@"ppe\Profiles\Default.ppx", Properties.Resources.ProxyYes);

            proxifier = new Process();
            proxifier.StartInfo.FileName = @"ppe\Proxifier.exe";
            proxifier.StartInfo.CreateNoWindow = true;
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Starting ppe\\Proxifier.exe");
            proxifier.Start();

            Console.ForegroundColor = ConsoleColor.Red;
            Console.Write("Installing certificate . . .");
            if(InstallCertificate())
            {
                Console.WriteLine("OK!"); 
            }
            else
            {
                Console.WriteLine("Failed to install certificate");
                while (true) { };
            }
         
           
           
            FiddlerApplication.BeforeRequest += new SessionStateHandler(FiddlerApplication_BeforeRequest);
            FiddlerApplication.BeforeResponse += new SessionStateHandler(FiddlerApplication_BeforeResponse);

            FiddlerCoreStartupSettingsBuilder Builder = new FiddlerCoreStartupSettingsBuilder();
            Builder.DecryptSSL();
            Builder.AllowRemoteClients();
            Builder.ListenOnPort(1800);
            FiddlerCoreStartupSettings Settings =  Builder.Build();
            CONFIG.IgnoreServerCertErrors = true;
            FiddlerApplication.Startup(Settings);

            startWpfLauncher();

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("- Login to NetEase!");

            while (!hacked) { }

            Console.ForegroundColor = ConsoleColor.DarkYellow;
            Console.WriteLine("China Minecraft HACKED by Silica :D");

            File.WriteAllBytes(@"ppe\Profiles\Default.ppx", Properties.Resources.ProxyNo);
            Thread.Sleep(20000);

            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("Shutting down proxy..");
            FiddlerApplication.Shutdown();

            Console.ForegroundColor = ConsoleColor.DarkMagenta;
            Console.Write("Uninstalling certificate . . .");
            if (UninstallCertificate())
            {
                Console.WriteLine("OK!");
            }
            else
            {
                Console.WriteLine("Failed to install certificate");
                while (true) { };
            }

            proxifier.Kill();

        }

        private static void FiddlerApplication_BeforeRequest(Session oSession)
        {
            if(oSession.uriContains("user-detail"))
            {
                Console.ForegroundColor = ConsoleColor.DarkBlue;
                Console.WriteLine("GET " + oSession.fullUrl + "");
                oSession.bBufferResponse = true;
            }
        }

        private static void FiddlerApplication_BeforeResponse(Session oSession)
        {
            
            if(oSession.uriContains("user-detail"))
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Spoofing response...");
                string ResponseBody = oSession.GetResponseBodyAsString();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Original: "+ResponseBody);
                dynamic jsonobject = JsonConvert.DeserializeObject(ResponseBody);
                jsonobject.entity.realname_status = 1;
                jsonobject.entity.isAntiAddiction = false;
                jsonobject.entity.need_realname_auth = false;
                jsonobject.entity.nickname_free = 0;
                jsonobject.entity.nickname_init = 1;
                jsonobject.entity.instruct_info = 0;
                string jsondata = JsonConvert.SerializeObject(jsonobject);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("New: " + jsondata);
                oSession.utilSetResponseBody(jsondata);
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine("Done!");
                hacked = true;
            }
        }
    }
}
