using System;
using System.Diagnostics;
using Microsoft.Web.Administration;
class IISFullSupportInstaller
{
    static void Main()
    {
        try
        {
            Console.WriteLine("正在检测IIS功能安装状态...");
            
            bool needRestart = false;
            
            // 安装缺失的功能
            if (!IsASPInstalled())
            {
                Console.WriteLine("检测到经典ASP功能未安装");
                InstallIISFeature("IIS-ASP");
                needRestart = true;
            }
            
            if (!IsASPNETInstalled())
            {
                Console.WriteLine("检测到ASP.NET功能未安装");
                InstallIISFeature("IIS-ASPNET45");
                needRestart = true;
            }
            
            // 配置IIS
            if (needRestart)
            {
                Console.WriteLine("需要重启后继续配置,按任意键重启计算机...");
                Console.ReadKey();
                RestartComputer();
            }
            else
            {
                ConfigureIIS();
                Console.WriteLine("ASP和ASP.NET支持已成功配置!");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"操作失败: {ex.Message}");
            Console.WriteLine("请以管理员身份运行此程序");
        }
    }
    // 检查经典ASP是否已安装
    static bool IsASPInstalled()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            try
            {
                // 尝试获取ASP配置部分,如果抛出异常说明未安装
                var aspSection = serverManager.GetApplicationHostConfiguration().GetSection("system.webServer/asp");
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
    // 检查ASP.NET是否已安装
    static bool IsASPNETInstalled()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            try
            {
                // 检查.NET Framework处理程序是否存在
                var config = serverManager.GetApplicationHostConfiguration();
                var runtimeSection = config.GetSection("system.webServer/runtime");
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
    // 安装IIS功能
    static void InstallIISFeature(string featureName)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = "dism.exe",
            Arguments = $"/Online /Enable-Feature /FeatureName:{featureName} /All /NoRestart",
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };
        using (Process process = new Process { StartInfo = startInfo })
        {
            Console.WriteLine($"正在安装 {featureName} ...");
            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();
            process.WaitForExit();
            if (process.ExitCode != 0)
            {
                throw new Exception($"{featureName} 安装失败 (代码 {process.ExitCode}): {error}");
            }
            
            if (!output.Contains("操作成功完成"))
            {
                throw new Exception($"{featureName} 安装未完成: " + output);
            }
            
            Console.WriteLine($"{featureName} 安装成功");
        }
    }
    // 配置IIS支持ASP和ASP.NET
    static void ConfigureIIS()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Console.WriteLine("正在配置IIS支持...");
            
            // 1. 配置经典ASP支持
            if (!IsASPConfigured(serverManager))
            {
                Console.WriteLine("配置经典ASP支持");
                ConfigureClassicASP(serverManager);
            }
            
            // 2. 配置ASP.NET支持
            if (!IsASPNETConfigured(serverManager))
            {
                Console.WriteLine("配置ASP.NET支持");
                ConfigureASPNET(serverManager);
            }
            
            // 3. 保存所有更改
            serverManager.CommitChanges();
            Console.WriteLine("配置保存成功");
        }
    }
    // 检查经典ASP是否已配置
    static bool IsASPConfigured(ServerManager serverManager)
    {
        try
        {
            var config = serverManager.GetApplicationHostConfiguration();
            var restrictions = config.GetSection("system.webServer/security/isapiCgiRestriction").GetCollection();
            
            foreach (var item in restrictions)
            {
                if (item["path"].ToString().EndsWith("asp.dll", StringComparison.OrdinalIgnoreCase) && 
                    (bool)item["allowed"])
                {
                    return true;
                }
            }
            return false;
        }
        catch
        {
            return false;
        }
    }
    // 配置经典ASP
    static void ConfigureClassicASP(ServerManager serverManager)
    {
        var config = serverManager.GetApplicationHostConfiguration();
        
        // 启用ASP ISAPI扩展
        var isapiSection = config.GetSection("system.webServer/security/isapiCgiRestriction");
        var restrictions = isapiSection.GetCollection();
        
        ConfigurationElement aspExtension = restrictions.CreateElement();
        aspExtension["path"] = @"%windir%\system32\inetsrv\asp.dll";
        aspExtension["allowed"] = true;
        aspExtension["description"] = "ASP Classic Support";
        restrictions.Add(aspExtension);
        // 配置ASP全局设置
        ConfigurationSection aspSection = config.GetSection("system.webServer/asp");
        aspSection["enableParentPaths"] = true;
        aspSection["bufferingOn"] = true;
        aspSection["scriptErrorSentToBrowser"] = true;
        // 为默认网站添加ASP处理程序映射
        Configuration webConfig = serverManager.GetWebConfiguration("Default Web Site");
        ConfigurationSection handlersSection = webConfig.GetSection("system.webServer/handlers");
        ConfigurationElementCollection handlers = handlersSection.GetCollection();
        ConfigurationElement aspHandler = handlers.CreateElement();
        aspHandler["name"] = "ASPClassic";
        aspHandler["path"] = "*.asp";
        aspHandler["verb"] = "GET,HEAD,POST";
        aspHandler["modules"] = "IsapiModule";
        aspHandler["scriptProcessor"] = @"%windir%\system32\inetsrv\asp.dll";
        aspHandler["resourceType"] = "File";
        handlers.Add(aspHandler);
    }
    // 检查ASP.NET是否已配置
    static bool IsASPNETConfigured(ServerManager serverManager)
    {
        try
        {
            var siteConfig = serverManager.GetWebConfiguration("Default Web Site");
            var handlers = siteConfig.GetSection("system.webServer/handlers").GetCollection();
            
            foreach (var handler in handlers)
            {
                if (handler["path"].ToString() == "*.aspx" && 
                    handler["type"] != null)
                {
                    return true;
                }
            }
            return false;
        }
        catch
        {
            return false;
        }
    }
    // 配置ASP.NET支持
    static void ConfigureASPNET(ServerManager serverManager)
    {
        // 设置应用程序池使用.NET 4.x
        bool poolExists = false;
        foreach (var pool in serverManager.ApplicationPools)
        {
            if (pool.Name == "DefaultAppPool")
            {
                pool.ManagedRuntimeVersion = "v4.0";
                pool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
                pool.AutoStart = true;
                pool.Enable32BitAppOnWin64 = true; // 根据需求设置
                poolExists = true;
                break;
            }
        }
        if (!poolExists)
        {
            ApplicationPool newPool = serverManager.ApplicationPools.Add("DefaultAppPool");
            newPool.ManagedRuntimeVersion = "v4.0";
            newPool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
        }
        // 确保默认网站使用正确的应用程序池
        Site defaultSite = serverManager.Sites["Default Web Site"];
        if (defaultSite != null)
        {
            defaultSite.ApplicationDefaults.ApplicationPoolName = "DefaultAppPool";
            
            // 添加ASP.NET处理程序映射
            Configuration siteConfig = serverManager.GetWebConfiguration("Default Web Site");
            ConfigurationSection handlersSection = siteConfig.GetSection("system.webServer/handlers");
            ConfigurationElementCollection handlers = handlersSection.GetCollection();
            
            // 检查是否已存在
            bool handlerExists = false;
            foreach (var handler in handlers)
            {
                if (handler["path"].ToString() == "*.aspx")
                {
                    handlerExists = true;
                    break;
                }
            }
            
            if (!handlerExists)
            {
                ConfigurationElement aspxHandler = handlers.CreateElement();
                aspxHandler["name"] = "ASP.NET";
                aspxHandler["path"] = "*.aspx";
                aspxHandler["verb"] = "*";
                aspxHandler["type"] = "System.Web.UI.PageHandlerFactory";
                aspxHandler["resourceType"] = "Unspecified";
                aspxHandler["requireAccess"] = "Script";
                handlers.Add(aspxHandler);
            }
        }
    }
    // 重启计算机
    static void RestartComputer()
    {
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = "shutdown.exe",
            Arguments = "/r /t 0",
            Verb = "runas", // 管理员权限
            UseShellExecute = true
        };
        try
        {
            Process.Start(startInfo);
            Environment.Exit(0);
        }
        catch (Exception ex)
        {
            throw new Exception($"重启失败: {ex.Message}\n请手动重启计算机以完成安装");
        }
    }
}