/// <summary>
        /// Executes the post install steps
        /// </summary>
        /// <param name="postStepDetails"></param>
        internal static void ExecutePostSteps(PostStepDetails postStepDetails)
        {
            InstallLogger installLogger = new InstallLogger(new RootLogger(Level.ALL));

            try
            {
                //Load the metadata from the update package
                MetadataView metedateView = UpdateHelper.LoadMetadata(postStepDetails.PostStepPackageFilename);
                List<ContingencyEntry> logMessages = new List<ContingencyEntry>();

                //Execute the post install steps
                DiffInstaller diffInstaller = new DiffInstaller(UpgradeAction.Upgrade);
                diffInstaller.ExecutePostInstallationInstructions(postStepDetails.PostStepPackageFilename, postStepDetails.HistoryPath, InstallMode.Update, metedateView, installLogger, ref logMessages);

                //Move the update package into the history folder
                File.Move(postStepDetails.PostStepPackageFilename, Path.Combine(postStepDetails.HistoryPath, Path.GetFileName(postStepDetails.PostStepPackageFilename)));
            }
            catch (Exception ex)
            {
                Log.Fatal("Post step execution failed", ex, "InstallPackage");
            }
            finally
            {
                //Write logs
                installLogger.WriteMessages(Path.Combine(postStepDetails.HistoryPath, "Install.log"));
            }
        }
        /// <summary>
        /// Writes the notification .json to the install folder
        /// </summary>
        /// <param name="status"></param>
        /// <param name="postStepDetails"></param>
        public static void NotifiyPackageComplete(string status, PostStepDetails postStepDetails)
        {
            try
            {
                using (StreamWriter sw = File.CreateText(postStepDetails.ResultFileName))
                {
                    CompletionNotification completionNotification = new CompletionNotification
                    {
                        Status = status,
                        ServerName = Environment.MachineName,
                        DeployHistoryPath = postStepDetails.HistoryPath
                    };

                    sw.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(completionNotification));
                }
            }
            catch (Exception ex)
            {
                Log.Fatal("Error posting to notification url", ex, typeof(InstallPackage));
            }
        }
        /// <summary>
        /// Creates a file that causes post install steps to be executed at startup
        /// </summary>
        /// <param name="updatePackageFilename"></param>
        /// <param name="historyPath"></param>
        private void RunPostStepsAtStartup(string updatePackageFilename, string historyPath)
        {
            string startupPostStepPackageFile = Path.Combine(_packageSource, STARTUP_POST_STEP_PACKAGE_FILENAME);

            //remove post step flag file if it exists
            if (File.Exists(startupPostStepPackageFile))
            {
                File.Delete(startupPostStepPackageFile);
            }

            PostStepDetails details = new PostStepDetails
            {
                HistoryPath = historyPath,
                PostStepPackageFilename = updatePackageFilename,
            };

            XmlSerializer serializer = new XmlSerializer(typeof(PostStepDetails));
            using (TextWriter writer = new StreamWriter(startupPostStepPackageFile))
            {
                serializer.Serialize(writer, details);
            }
        }
        /// <summary>
        /// Installs the packages found in the package source folder.
        /// </summary>
        private void InstallPackages()
        {
            //Check to see if there is a post-step pending, and skip package install if there is
            if (File.Exists(Path.Combine(_packageSource, STARTUP_POST_STEP_PACKAGE_FILENAME)))
            {
                Log.Info("Install packages skipped because there is a post step pending", this);

                return;
            }

            InstallLogger installLogger = new InstallLogger(new RootLogger(Level.ALL));

            //Return if another installation is happening
            if (GetInstallerState() != InstallerState.Ready)
            {
                Log.Info(string.Format("Install packages skipped because install state is {0}. ", GetInstallerState()), this);

                return;
            }

            //Block further package installs
            SetInstallerState(InstallerState.InstallingPackage);

            using (new SecurityDisabler())
            {
                //Find pending packages. This loop may not complete if there were binary/config changes
                foreach (string updatePackageFilename in Directory.GetFiles(_packageSource, "*.update", SearchOption.TopDirectoryOnly).OrderBy(f => f))
                {
                    string updatePackageFilenameStripped = updatePackageFilename.Split('\\').Last();
                    if (ShutdownDetected)
                    {
                        Log.Info("Install packages aborting due to shutdown", this);

                        break;
                    }

                    //Prevent shutdown
                    using (new ShutdownGuard())
                    {
                        Log.Info(String.Format("Begin Installation: {0}", updatePackageFilenameStripped), this);
                        PackageInstallationInfo installationInfo = new PackageInstallationInfo
                        {
                            Action = UpgradeAction.Upgrade,
                            Mode = InstallMode.Install,
                            Path = updatePackageFilename
                        };

                        string installationHistoryRoot = null;
                        List<ContingencyEntry> logMessages = new List<ContingencyEntry>();

                        PostStepDetails postStepDetails = new PostStepDetails
                        {
                            PostStepPackageFilename = updatePackageFilename,
                            ResultFileName = Path.Combine(Path.GetDirectoryName(updatePackageFilename), Path.GetFileNameWithoutExtension(updatePackageFilename) + ".json")
                        };

                        string installStatus = null;

                        try
                        {
                            //Run the installer
                            logMessages = UpdateHelper.Install(installationInfo, installLogger, out installationHistoryRoot);
                            postStepDetails.HistoryPath = installationHistoryRoot;

                            if (_updateConfigurationFiles)
                            {
                                FindAndUpdateChangedConfigs(Path.GetFileNameWithoutExtension(updatePackageFilename));
                            }

                            //Sleep for 4 seconds to see if there was a file change that could cause a problem
                            Thread.Sleep(4000);

                            //Abort if Sitecore is shutting down. The install post steps will have to be completed later
                            if (ShutdownDetected)
                            {
                                SetInstallerState(InstallerState.WaitingForPostSteps);

                                RunPostStepsAtStartup(updatePackageFilename, installationHistoryRoot, postStepDetails);

                                RestartSitecoreServer();

                                break;
                            }
                            else
                            {
                                ExecutePostSteps(installLogger, postStepDetails);
                                installStatus = SUCCESS;

                                Log.Info(String.Format("Installation Complete: {0}", updatePackageFilenameStripped), this);
                                SetInstallerState(InstallerState.Ready);
                            }
                        }
                        catch (PostStepInstallerException ex)
                        {
                            installStatus = FAIL;

                            logMessages = ex.Entries;
                            installationHistoryRoot = ex.HistoryPath;
                            installLogger.Fatal("Package install failed", ex);

                            throw ex;
                        }
                        catch (Exception ex)
                        {
                            installStatus = FAIL;
                            Log.Error(String.Format("Installation Failed: {0}", updatePackageFilenameStripped), ex, this);
                            installLogger.Fatal("Package install failed", ex);

                            ThreadPool.QueueUserWorkItem(new WaitCallback((ctx) =>
                            {
                                try
                                {
                                    //The update package may be locked because the file object hasn't been disposed. Wait for it.
                                    Thread.Sleep(100);

                                    //I really hate this, but I couldn't find another reliable way to ensure the locked file is closed before I move it.
                                    GC.Collect(2);
                                    GC.WaitForPendingFinalizers();

                                    File.Move(updatePackageFilename, updatePackageFilename + ".error_" + DateTime.Now.ToString("yyyyMMdd.hhmmss"));
                                }
                                catch (Exception ex1)
                                {
                                    Log.Error("Error moving broken package", ex1, this);
                                }
                            }));

                            break;
                        }
                        finally
                        {
                            if (installationHistoryRoot != null)
                            {
                                //Write logs
                                installLogger.WriteMessages(Path.Combine(installationHistoryRoot, "Install.log"));

                                SaveInstallationMessages(installationHistoryRoot, logMessages);
                            }

                            //Send the status if there is one
                            if (installStatus != null)
                            {
                                NotifiyPackageComplete(installStatus, postStepDetails);
                            }
                        }
                    }
                }

                if (!ShutdownDetected)
                {
                    //Allow additional installs
                    SetInstallerState(InstallerState.Ready);
                }
            }
        }