using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;
using System.Data.SqlClient;
using System.ServiceProcess;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using Microsoft.Win32;
using System.Drawing;

namespace PosStart
{
    /// <summary>
    /// frmPosStart
    /// </summary>
    public partial class frmPosStart : Form
    {
        #region 변수 선언
        /// <summary>
        /// PROCESS_INFORMATION
        /// </summary>
        public struct PROCESS_INFORMATION
        {
            /// <summary> hProcess </summary>
            public IntPtr hProcess;
            /// <summary> hThread </summary>
            public IntPtr hThread;
            /// <summary> dwProcessId </summary>
            public uint dwProcessId;
            /// <summary> dwThreadId </summary>
            public uint dwThreadId;
        }

        /// <summary>
        /// STARTUPINFO
        /// </summary>
        public struct STARTUPINFO
        {
            /// <summary> cb </summary>
            public uint cb;
            /// <summary> lpReserved </summary>
            public string lpReserved;
            /// <summary> lpDesktop </summary>
            public string lpDesktop;
            /// <summary> lpTitle </summary>
            public string lpTitle;
            /// <summary> dwX </summary>
            public uint dwX;
            /// <summary> dwY </summary>
            public uint dwY;
            /// <summary> dwXSize </summary>
            public uint dwXSize;
            /// <summary> dwYSize </summary>
            public uint dwYSize;
            /// <summary> dwXCountChars </summary>
            public uint dwXCountChars;
            /// <summary> dwYCountChars </summary>
            public uint dwYCountChars;
            /// <summary> dwFillAttribute </summary>
            public uint dwFillAttribute;
            /// <summary> dwFlags </summary>
            public uint dwFlags;
            /// <summary> wShowWindow </summary>
            public short wShowWindow;
            /// <summary> cbReserved2 </summary>
            public short cbReserved2;
            /// <summary> lpReserved2 </summary>
            public IntPtr lpReserved2;
            /// <summary> hStdInput </summary>
            public IntPtr hStdInput;
            /// <summary> hStdOutput </summary>
            public IntPtr hStdOutput;
            /// <summary> hStdError </summary>
            public IntPtr hStdError;
        }

        [DllImport("kernel32.dll")]
        static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes,
            bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
        #endregion 

        #region 생성자
        /// <summary> frmPosStart </summary>
        public frmPosStart()
        {
            InitializeComponent();

            base.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw, true);
            //this.UpdateStyles();
        }
        #endregion 

        #region 폼초기화
        /// <summary>
        /// Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmPosStart_Load(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < Screen.AllScreens.Length; i++)
                {
                    if (Screen.AllScreens[i].Primary == true)                       // 캐셔화면
                    {
                        this.Top = 0;
                        this.Left = 0;
                        this.Width = Screen.AllScreens[i].WorkingArea.Width;
                        this.Height = Screen.AllScreens[i].WorkingArea.Height;
                        break;
                    }
                }

                // 브랜드 백이미지 로딩
                DirectoryInfo directories = Directory.GetParent(Directory.GetCurrentDirectory());
                
                string sFileName = directories.FullName + @"\CDP\CDP_COM\" + "intro_bimg000.png";
                if (File.Exists(sFileName) == true)
                {
                    this.BackgroundImage = Image.FromFile(sFileName);
                }
            }
            catch (Exception ex)
            {
                WriteLogFile("frmPosStart_Load.Exception." + ex.Message);
            }
            finally
            {
                this.Tag = "START";
            }
        }
        #endregion 

        #region 프로그램 시작
        private void frmPosStart_Activated(object sender, EventArgs e)
        {
            bool bRet = false;
            int iMaxJob = 6;

            try
            {   
                if (this.Tag.ToString() != "START") return;
                this.Tag = "";

                #region 1.메인 프로그램 강제 종료
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // 메인 프로그램 강제 종료
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                try
                {
                    //POS Program 강제 종료
                    Process[] arPosPgm = Process.GetProcessesByName("PosMain");
                    foreach (Process pPosPgm in arPosPgm)
                    {
                        //Thread.Sleep(2000);
                        pPosPgm.Kill();

                        SetProgreeBar(1, iMaxJob);

                        Thread.Sleep(1000);
                    }

                    //O2MSR 강제 종료(2017.07.03)
                    //Process[] arO2Msr = Process.GetProcessesByName("O2MSR");
                    //foreach (Process pO2Msr in arO2Msr)
                    //{
                    //    pO2Msr.Kill();

                    //    Thread.Sleep(1000);
                    //}
                }
                catch (Exception ex)
                {
                    WriteLogFile("frmPosStart_Activated.Exception.PosMain Force End." + ex.Message);
                }
                #endregion

                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // 프로그램 복사
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                try
                {
                    #region 2.다운로드된 프로그램 파일 복사
                    // 현재 디렉토리 
                    DirectoryInfo dirParent = Directory.GetParent(Directory.GetCurrentDirectory());

                    //#Rhee, 20180108 중국서버주소 변경 추가 start
                    // 프로그램 버전 INI 파일 설정
                    CmMessage cmPosConfig2 = CmMessage.MakeMessageFromFile(dirParent.FullName + @"\INI\PosConfig.INI");
                    string sCommSvrIp = cmPosConfig2.GetMessage("SERVER").GetMessageValue("CommSvrIp");
                    string sCmpCd = cmPosConfig2.GetMessage("POS").GetMessageValue("CmpCd");

                    //#20180125 윈도우 자동 업데이트 해제 기능 전체 적용 start
                    //기존
                    /*
                    if (sCmpCd == "PCCN")
                    {
                        AutoWindowsUpdateStop();
                    }
                    */
                    //변경
                    AutoWindowsUpdateStop();
                    //#20180125 윈도우 자동 업데이트 해제 기능 전체 적용 end

                    if ((sCmpCd == "PCCN") && (sCommSvrIp == "118.26.25.100"))
                    {
                        cmPosConfig2.GetMessage("SERVER").MakeMessageOverWrite("CommSvrIp", "pos.spcchinapos.com");
                        cmPosConfig2.MakeFileFromMessage(dirParent.FullName + @"\INI\PosConfig.INI");
                    }
                    //#Rhee, 20180108 중국서버주소 변경 추가 end
                    
                    //#Rhee, 20180227 미국 환경설정 변경 start
                    if (sCmpCd == "PCUS")
                    {
                        cmPosConfig2.GetMessage("GLOBAL").MakeMessageOverWrite("FontFix", "SimSun");        // 기본 폰트 변경
                        cmPosConfig2.MakeFileFromMessage(dirParent.FullName + @"\INI\PosConfig.INI");

                        CmMessage cmPosDevice = CmMessage.MakeMessageFromFile(dirParent.FullName + @"\INI\PosDevice.INI");
                        cmPosDevice.GetMessage("ICREADER").MakeMessageOverWrite("UseFlag", "0");            // ICREADER 기본 비사용
                        cmPosDevice.MakeFileFromMessage(dirParent.FullName + @"\INI\PosDevice.INI");
                    }
                    //#Rhee, 20180227 미국 환경설정 변경 end

                    // 프로그램 적용파일 존재시 
                    if (Directory.Exists(dirParent.FullName + @"\DOWN\PGM\"))
                    {
                        // BIN 백업 (BIN ==> BACK/BIN)
                        // MoonSeokWoo 
                        //*** MoonSeokWoo 2017.12.19 Edit Bin 폴더 백업 제거.                        
                        WriteLogFile("frmPosStart_Activated.BinBack.Start : Step1 NoBackUp");
                        //bRet = DirectoryCopy(dirParent.FullName + @"\BIN\", dirParent.FullName + @"\BACK\BIN\", "", false, null);
                        bRet = true;    //백업 성공 유무와 관계 없이 진행 해야 하므로 무조건 true.
                        WriteLogFile("frmPosStart_Activated.BinBack.Start : Step1 Result -> After 2017.12.19 :" + bRet.ToString());                        
                        //*** MoonSeokWoo 2017.12.19 Edit End

                        if (bRet == true)
                        {
                            // 다운로드된 프로그램 파일 복사
                            // MoonSeokWoo
                            WriteLogFile("frmPosStart_Activated.BinBack.Start : Step2");
                            bRet = DirectoryCopy(dirParent.FullName + @"\DOWN\PGM\", dirParent.FullName + @"\", "", false, "PosStart.exe");
                            //bRet = DirectoryCopy(dirParent.FullName + @"\DOWN\PGM\", dirParent.FullName + @"\", "", true, "PosStart.exe");
                            WriteLogFile("frmPosStart_Activated.BinBack.Start : Step2 Result -> After 2017.12.19 " + bRet.ToString());
                            //*** MoonSeokWoo 2017.12.19 복사 실패시 복원하지 않음 ( 복원할 대상이 존재하지 않음).
                            bRet = true;
                            WriteLogFile("frmPosStart_Activated.BinBack.Start : Step3 Result -> After 2017.12.19 absolute True! ");
                            //*** MoonSeokWoo 2017.12.19 복사 실패는 없다고 보고 감.
                            if (bRet != true)
                            {
                                // 복사 오류시 백업복구
                                WriteLogFile("tmrStartProc.Exception.Pos Program Rollback." + " 복사 오류로 인해 백업 복구");

                                DirectoryCopy(dirParent.FullName + @"\BACK\BIN\", dirParent.FullName + @"\BIN\", "", true, "PosStart.exe");
                            }
                            else
                            {
                                try
                                {
                                    // 복사 오류 확인을 위해 폴더 삭제 주석 처리(20170927)
                                    // 폴더 삭제
                                    //Directory.Delete(dirParent.FullName + @"\DOWN\PGM\", true);
                                    if(Directory.Exists(dirParent.FullName + @"\DOWN\PGM_BACK\") == true)
                                    {
                                        Directory.Delete(dirParent.FullName + @"\DOWN\PGM_BACK\", true);
                                        System.Threading.Thread.Sleep(300);                                        
                                    }

                                    Directory.Move(dirParent.FullName + @"\DOWN\PGM\", dirParent.FullName + @"\DOWN\PGM_BACK\");
                                    System.Threading.Thread.Sleep(1000); 
                                }
                                catch(Exception ex)
                                { }

                                // 프로그램 버전 INI 파일 설정
                                CmMessage cmPosConfig = CmMessage.MakeMessageFromFile(dirParent.FullName + @"\INI\PosConfig.INI");
                                string sVer = cmPosConfig.GetMessage("PGMVER").GetMessageValue("ProgramVer_Update");
                                string sSeq = cmPosConfig.GetMessage("PGMVER").GetMessageValue("ProgramVerSeq_Update");

                                if (sVer.Length > 0)
                                {
                                    cmPosConfig.GetMessage("PGMVER").MakeMessageOverWrite("ProgramVer10", sVer);
                                    cmPosConfig.GetMessage("PGMVER").MakeMessageOverWrite("ProgramVerSeq10", sSeq);
                                    cmPosConfig.GetMessage("PGMVER").MakeMessageOverWrite("ProgramVer_Update", "");
                                    cmPosConfig.GetMessage("PGMVER").MakeMessageOverWrite("ProgramVerSeq_Update", "");

                                    cmPosConfig.MakeFileFromMessage(dirParent.FullName + @"\INI\PosConfig.INI");
                                }
                            }
                        }
                    }
                    SetProgreeBar(2, iMaxJob);
                    #endregion
                    WriteLogFile("frmPosStart_Activated.Start : Step4 Result -> After 2017.12.19 Add ");
                    #region 3.다운로드된 동영상/이미지 파일 복사
                    // 다운로드된 동영상/이미지 파일 복사
                    DirectorySubCopy(dirParent.FullName + @"\DOWN\CDP\CAMPAIGN\", dirParent.FullName + @"\CDP\CAMPAIGN\", "", true);
                    DirectorySubCopy(dirParent.FullName + @"\DOWN\CDP\CDP_COM\", dirParent.FullName + @"\CDP\CDP_COM\", "", true);
                    DirectorySubCopy(dirParent.FullName + @"\DOWN\CDP\CUSTOMER\", dirParent.FullName + @"\CDP\CUSTOMER\", "", true);
                    DirectorySubCopy(dirParent.FullName + @"\DOWN\CDP\ITEM\", dirParent.FullName + @"\CDP\ITEM\", "", true);
                    DirectorySubCopy(dirParent.FullName + @"\DOWN\CDP\TEST_MODE\", dirParent.FullName + @"\CDP\TEST_MODE\", "", true);
                    SetProgreeBar(3, iMaxJob);
                    #endregion
                    WriteLogFile("frmPosStart_Activated.End : Step4 Result -> After 2017.12.19 Add ");

                    WriteLogFile("frmPosStart_Activated.Start : Step5 Result -> After 2017.12.19 Add ");
                    #region 4. 인증버전 판단 프로그램 복사
                    CmMessage cmDeviceInfo = CmMessage.MakeMessageFromFile(dirParent.FullName + @"\INI\PosDevice.INI");
                    string sICReaderUseYn = cmDeviceInfo.GetMessage("ICREADER").GetMessageValue("UseFlag");

                    //#20171122 IC, MSR폴더에 있는 SpcnPos로 시작하는 파일 삭제 start
                    DirectoryFileDelete(dirParent.FullName + @"\BIN\IC\", "SpcnPos");
                    DirectoryFileDelete(dirParent.FullName + @"\BIN\MSR\", "SpcnPos");
                    //#20171122 IC, MSR폴더에 있는 SpcnPos로 시작하는 파일 삭제 end
                    
                    // 인증버전 판단
                    if (sICReaderUseYn == "1")
                    {
                        // ic폴더에 있는 Cosmos로 시작하는 dll 삭제 (본 파일은 실제 bin에 포함되어 있음)
                        DirectoryFileDelete(dirParent.FullName + @"\BIN\IC\", "Cosmos");

                        // update 적용
                        DirectoryCopy(dirParent.FullName + @"\BIN\IC\", dirParent.FullName + @"\BIN\", "", false, null);     // IC 버전
                    }
                    else
                    {
                        // msr폴더에 있는 Cosmos로 시작하는 dll 삭제 (본 파일은 실제 bin에 포함되어 있음)
                        DirectoryFileDelete(dirParent.FullName + @"\BIN\MSR\", "Cosmos");

                        // update 적용
                        DirectoryCopy(dirParent.FullName + @"\BIN\MSR\", dirParent.FullName + @"\BIN\", "", false, null);    // MSR 버전
                    }
                    SetProgreeBar(4, iMaxJob);
                    #endregion
                    WriteLogFile("frmPosStart_Activated.End : Step5 Result -> After 2017.12.19 Add ");

                    #region 5.OCX 등록 처리
                    // 넥사크로 DLL 삭제
                    if (File.Exists(dirParent.FullName + @"\BIN\nexacroax14.dll") == true) File.Delete(dirParent.FullName + @"\BIN\nexacroax14.dll");

                    // OCX 등록 처리
                    DllRegSvr32(dirParent.FullName + @"\BIN");
                    DllRegSvr32(@"C:\Program Files\OPOS\CommonCO");
                    DllRegSvr32(@"C:\Program Files (x86)\OPOS\CommonCO");

                    // 넥사크로 DLL 등록
                    DllRegSvr32(@"C:\Program Files\nexacro\14");
                    DllRegSvr32(@"C:\Program Files (x86)\nexacro\14");

                    // grayber@20180115 ADODB.DLL 추가 start

                    //#20180223 인천공항T2 연동 정보 설정된 경우만 등록 start
                    //기존
                    DLLGacutil(dirParent.FullName + @"\BIN");
                    //변경
                    /*
                    if (File.Exists(dirParent.FullName + @"\INI\IncheonAirPort.INI"))
                    {
                        CmMessage cmIncheonAirPort = CmMessage.MakeMessageFromFile(dirParent.FullName + @"\INI\IncheonAirPort.INI");
                        string sAirportIP = cmIncheonAirPort.GetMessage("INCHEONAIRPORT").GetMessageValue("AirportIP");
                        string sAirportUser = cmIncheonAirPort.GetMessage("INCHEONAIRPORT").GetMessageValue("AirportUser");
                        string sAirportPass = cmIncheonAirPort.GetMessage("INCHEONAIRPORT").GetMessageValue("AirportPass");
                        string sAirportComp = cmIncheonAirPort.GetMessage("INCHEONAIRPORT").GetMessageValue("AirportComp");
                        string sAirportStore = cmIncheonAirPort.GetMessage("INCHEONAIRPORT").GetMessageValue("AirportStore");
                        string sAirportPosNo = cmIncheonAirPort.GetMessage("INCHEONAIRPORT").GetMessageValue("AirportPosNo");

                        if ((sAirportIP != "" && sAirportIP != null) &&
                            (sAirportUser != "" && sAirportIP != null) &&
                            (sAirportPass != "" && sAirportIP != null) &&
                            (sAirportComp != "" && sAirportIP != null) &&
                            (sAirportStore != "" && sAirportIP != null) && 
                            (sAirportPosNo  != "" && sAirportIP != null))
                        {
                            DLLGacutil(dirParent.FullName + @"\BIN");
                        }
                    }
                    */
                    //#20180223 인천공항T2 연동 정보 설정된 경우만 등록 end

                    // grayber@20180115 ADODB.DLL 추가 start


                    SetProgreeBar(5, iMaxJob);
                    #endregion


                    //#20180309 불필요한파일삭제 start,phj
                    #region 불필요한 파일 삭제
                    /*
                    if (UnnecessaryFileDelete() == true)
                    {
                        WriteLogFile("frmPosStart_Activated.End : UnnecessaryFileDelete Result true");
                    }
                    else
                    {
                        WriteLogFile("frmPosStart_Activated.End : UnnecessaryFileDelete Result false");
                    }
                    */
                    #endregion
                    //#20180309 불필요한파일삭제 end,phj

                    //#15993 PB 강동역_환경설정 세팅 변경된 원인파악 요청 start

                    WriteLogFile("frmPosStart_Activated.Start : Step6 Result -> After 2018.07.24 Add ");
                   
                    #region 
                    if (UnnecessaryExeFileDelete() == true)
                    {
                        WriteLogFile("frmPosStart_Activated.Start : Step6 Result -> true ");
                    }
                    else
                    {
                        WriteLogFile("frmPosStart_Activated.Start : Step6 Result -> false ");
                    }
                    #endregion
                    
                    WriteLogFile("frmPosStart_Activated.End   : Step6 Result -> After 2018.07.24 Add ");

                    //#15993 PB 강동역_환경설정 세팅 변경된 원인파악 요청 end
                }
                catch (Exception ex)
                {
                    WriteLogFile("frmPosStart_Activated.Exception.Pos Program Copy." + ex.Message);
                }

                #region 6.POS 프로그램 실행
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // POS 프로그램 실행
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                try
                {
                    Thread.Sleep(1000);

                    //POS POS Program 실행
                    ProcessStartInfo startInfo = new ProcessStartInfo("PosMain.exe");
                    //startInfo.WindowStyle = ProcessWindowStyle.Maximized;
                    startInfo.CreateNoWindow = false;
                    Process.Start(startInfo);

                    SetProgreeBar(6, iMaxJob);
                }
                catch (Exception ex)
                {
                    WriteLogFile("frmPosStart_Activated.Exception.PosMain Start." + ex.Message);
                }
                #endregion
            }
            catch (Exception ex)
            {
                WriteLogFile("frmPosStart_Activated.Exception." + ex.Message);
            }
            finally
            {
                this.Close();
                Application.Exit();
            }
        }        
        #endregion 

        //#20180309 불필요한파일삭제 start,phj
        #region 불필요한파일삭제
        /*
        public bool UnnecessaryFileDelete()
        {
            bool bRet = false;
            try
            {
                // 현재 디렉토리 
                DirectoryInfo dirParent = Directory.GetParent(Directory.GetCurrentDirectory());

                // 대상 폴더 
                string sSrcPath = dirParent.FullName + @"\BIN\";

                if (Directory.Exists(sSrcPath))
                {
                    DirectoryInfo di = new DirectoryInfo(sSrcPath);
                    if (di.Exists)
                    {
                        foreach (FileInfo fi in di.GetFiles())
                        {
                            string sFilExtension = Path.GetExtension(sSrcPath + fi.Name);

                            //확장자가 .pdb 또는 .XML이거나
                            //실행파일이 NewPosInstaller.exe 또는 NewPosInstallerStart.exe 또는 PosDesign800.exe
                            //현재 BIN 폴더에서 삭제하도록 함 
                            if (fi.Extension.ToLower().CompareTo(".pdb") == 0 || fi.Extension.ToLower().CompareTo(".xml") == 0 ||
                                fi.Name == "PosDesign800.exe" || fi.Name == "NewPosInstaller.exe" || fi.Name == "NewPosInstallerStart.exe")
                            {
                                fi.Delete();
                            }

                            if (fi.Name == "PosDesign800.exe" || fi.Name == "NewPosInstaller.exe" || fi.Name == "NewPosInstallerStart.exe")
                            {
                                fi.Delete();
                            }
                        }
                    }
                }
                else
                {
                    WriteLogFile("UnnecessaryFileDelete -> BIN 폴더가 존재하지 않습니다.");
                }

                bRet = true;
            }
            catch (Exception ex)
            {
                WriteLogFile("UnnecessaryFileDelete -> Exception : " + ex.Message);
                bRet = false;
            }

            return bRet;
        }
        */
        #endregion
        //#20180309 불필요한파일삭제 end,phj
        
        //#Rhee, 20180111 윈도우 자동업데이트 정지 추가 start
        #region 윈도우 자동업데이트 정지
        /// <summary>
        /// 윈도우 자동업데이트 정지
        /// </summary>
        private void AutoWindowsUpdateStop()
        {
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // BAT 프로그램 실행
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            try
            {
                Thread.Sleep(1000);

                //#20180209 윈도우 자동업데이트 정지 기능 이미 적용된 경우 넘어가도록 수정 start
                //기존
                /*
                //윈도우즈 자동업데이트 정지 추가
                WriteLogFile("Directory GetCurrentDirectory : " + Directory.GetCurrentDirectory().ToString());

                if (File.Exists(Directory.GetCurrentDirectory() + @"\AutoUpdateStop.bat") != true)
                {
                    ProcessStartInfo cmdinfo = new ProcessStartInfo("AutoUpdateStop.bat");

                    cmdinfo.WorkingDirectory = @"C:\SPC\POS\BIN\";                    
                    cmdinfo.CreateNoWindow = false;
                    cmdinfo.Verb = "runas";
                    cmdinfo.WindowStyle = ProcessWindowStyle.Hidden;
                    Process.Start(cmdinfo);
                }
                else
                {
                    ProcessStartInfo cmdinfo = new ProcessStartInfo();
                    Process process = new Process();
                                        
                    cmdinfo.CreateNoWindow = true;
                    cmdinfo.UseShellExecute = false;
                    cmdinfo.RedirectStandardOutput = true;
                    cmdinfo.RedirectStandardInput = true;
                    cmdinfo.RedirectStandardError = true;
                    cmdinfo.FileName = @"cmd";
                    cmdinfo.Verb = "runas";
                   
                    process.StartInfo = cmdinfo;
                    process.Start();

                    process.StandardInput.Write(@"sc Stop WuauServ " + Environment.NewLine);
                    process.StandardInput.Write(@"REG add ""HKLM\SYSTEM\CurrentControlSet\services\wuauserv"" /v Start /t REG_DWORD /d 4 /f " + Environment.NewLine);
                    process.StandardInput.Close();
                    string resultValue = process.StandardOutput.ReadToEnd();
                    process.WaitForExit();
                    process.Close();
                    Console.WriteLine(resultValue);
                }              
                */
                //변경
                //이미 윈도우 자동업데이트 해제한 경우 실행하지 않는다.
                var keyName = @"SYSTEM\CurrentControlSet\services\wuauserv";
                string sRegData = "";
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(keyName))
                {
                    sRegData = key.GetValue("Start", "0").ToString();
                    if (sRegData == "4")
                    {
                        WriteLogFile("AutoUpdateStop_Activated : already");
                        return;                      
                    }                
                }

                string dirPath = Directory.GetCurrentDirectory();

                //윈도우즈 자동업데이트 정지 추가
                WriteLogFile("Directory GetCurrentDirectory : " + dirPath.ToString());

                if (File.Exists(dirPath + @"\AutoUpdateStop.bat") == true)
                {
                    ProcessStartInfo cmdinfo = new ProcessStartInfo("AutoUpdateStop.bat");

                    cmdinfo.WorkingDirectory = dirPath;
                    cmdinfo.CreateNoWindow = false;
                    cmdinfo.Verb = "runas";
                    cmdinfo.WindowStyle = ProcessWindowStyle.Hidden;
                    Process.Start(cmdinfo);
                }
                else
                {
                    ProcessStartInfo cmdinfo = new ProcessStartInfo();
                    Process process = new Process();

                    cmdinfo.CreateNoWindow = true;
                    cmdinfo.UseShellExecute = false;
                    cmdinfo.RedirectStandardOutput = true;
                    cmdinfo.RedirectStandardInput = true;
                    cmdinfo.RedirectStandardError = true;
                    cmdinfo.FileName = @"cmd";
                    cmdinfo.Verb = "runas";

                    process.StartInfo = cmdinfo;
                    process.Start();

                    process.StandardInput.Write(@"sc Stop WuauServ " + Environment.NewLine);
                    process.StandardInput.Write(@"REG add ""HKLM\SYSTEM\CurrentControlSet\services\wuauserv"" /v Start /t REG_DWORD /d 4 /f " + Environment.NewLine);
                    process.StandardInput.Close();
                    string resultValue = process.StandardOutput.ReadToEnd();
                    process.WaitForExit();
                    process.Close();
                    Console.WriteLine(resultValue);
                }              

                //#20180209 윈도우 자동업데이트 정지 기능 이미 적용된 경우 넘어가도록 수정 end
                
                WriteLogFile("AutoUpdateStop_Activated : AutoUpdateStop.bat Run - OK");
            }
            catch (Exception ex)
            {
                WriteLogFile("AutoUpdateStop_Activated.Exception.AutoUpdateStop Run." + ex.Message);
            }           
        }
        #endregion
        //#Rhee, 20180111 윈도우 자동업데이트 정지 추가 end

        #region 디렉토리의 모든 파일복사 처리
        /// <summary>
        /// 디렉토리의 모든 파일복사 처리
        /// </summary>
        /// <param name="sFileName"></param>
        /// <param name="sSrcPath"></param>
        /// <param name="sDstPath"></param>
        /// <param name="sBackPath"></param>
        /// <param name="bDelete"></param>
        /// <returns></returns>
        public bool FileCopy(string sFileName, string sSrcPath, string sDstPath, string sBackPath, bool bDelete)
        {
            bool bRet = false;
            try
            {
                try
                {
                    if (sBackPath.Length > 0)
                    {
                        File.Delete(sBackPath + sFileName);
                        File.Move(sDstPath + sFileName, sBackPath + sFileName);   // 기존파일 이동 처리
                    }

                }
                catch(Exception e)
                {
                    WriteLogFile("FileCopy.Exception.1." + e.Message);
                    WriteLogFile("FileCopy.Exception.1.FileName : " + sFileName);
                    return bRet;
                }

                File.Copy(sSrcPath + sFileName, sDstPath + sFileName, true);            // 파일복사 처리
                if ( bDelete == true) File.Delete(sSrcPath + sFileName);

                bRet = true;
            }
            catch (Exception ex)
            {
                WriteLogFile("FileCopy.Exception.2." + ex.Message);
                WriteLogFile("FileCopy.Exception.2.FileName : " + sFileName);
                bRet = false;
            }
            return bRet;
        }
        #endregion 

        #region 디렉토리 복사
        /// <summary>
        /// 디렉토리 복사
        /// </summary>
        /// <param name="sSrcPath"></param>
        /// <param name="sDstPath"></param>
        /// <param name="sBackPath"></param>
        /// <param name="bDelete"></param>
        /// <param name="sNotCopyFileName"></param>
        /// <returns></returns>
        public bool DirectoryCopy(string sSrcPath, string sDstPath, string sBackPath, bool bDelete, string sNotCopyFileName)
        {
            bool bRet = false;
            try
            {
                if (Directory.Exists(sDstPath) == false) Directory.CreateDirectory(sDstPath);
                if (sBackPath.Length > 0 && Directory.Exists(sBackPath) == false) Directory.CreateDirectory(sBackPath);

                DirectoryInfo di = new DirectoryInfo(sSrcPath);
                if (di.Exists)
                {
                    foreach (FileInfo fi in di.GetFiles())
                    {
                        //*** MoonSeokWoo 2017.12.20 Edit 파일비교 대문자로 변경해서 하도록 수정.
                        if (fi.Name.ToUpper() == "lpk.dll".ToUpper()) continue;     // 삭제되지 않은 파일 존재시 오류처리 되어 Skip
                        //*** MoonSeokWoo 2017.12.20 Edit 파일비교 대문자로 변경해서 하도록 수정. fi.Name == sNotCopyFileName
                        if(sNotCopyFileName != null)
                        {
                            if (sNotCopyFileName != "" && fi.Name.ToUpper() == sNotCopyFileName.ToUpper()) continue;
                        }
                        
                        bRet = FileCopy(fi.Name, sSrcPath, sDstPath, sBackPath, bDelete);

                        if (bRet != true)
                        {
                            //MoonSeokWoo
                            WriteLogFile("frmPosStart_DirectoryCopy.GetFiles fail -> " + fi.Name);
                            //사용중인 파일이 있다면 로그만 남기고 계속 진행.
                            //break;
                        } 
                        
                    }

                    foreach (DirectoryInfo fi in di.GetDirectories())
                    {
                        //*** 지정된 폴더는 복사 제외 spcn요청 
                        if (fi.Name.ToUpper() == "spcn_log".ToUpper() || fi.Name.ToUpper() == "spcncat_log".ToUpper() || fi.Name.ToUpper() == "spcndg_log".ToUpper() || fi.Name.ToUpper() == "SpcnLog".ToUpper()
                            || fi.Name.ToUpper() == "spcnsecu_log".ToUpper() || fi.Name.ToUpper() == "dualPlayerLog".ToUpper() || fi.Name.ToUpper() == "log".ToUpper() || fi.Name.ToUpper() == "PipeLog".ToUpper()
                            || fi.Name.ToUpper() == "O2MsrLog".ToUpper()) continue;
                        //*** 지정된 폴더는 복사 제외 spcn요청 

                        bRet = DirectoryCopy(sSrcPath + fi.Name + @"\", sDstPath + fi.Name + @"\", sBackPath.Length == 0 ? "" : sBackPath + fi.Name + @"\", bDelete, sNotCopyFileName);
                        if (bRet != true)
                        {
                            //MoonSeokWoo
                            WriteLogFile("frmPosStart_DirectoryCopy.GetDirectories fail -> " + fi.Name);
                            //*** 2017.12.19
                            //복사 실패한 폴더 존재시 다음 폴더 작업 하지 않고 넘어가는 부분 수정
                            //break; 
                        }

                        try
                        {
                            if (bDelete == true) Directory.Delete(sSrcPath + fi.Name);
                        }
                        catch(Exception ex)
                        {
                            WriteLogFile("Directory Delete Exception in DirectoryCopy Method - " + ex.Message);
                        }
                    }

                    //if (bDelete == true) Directory.Delete(sSrcPath);
                }
                bRet = true;
            }
            catch (Exception ex)
            {
                WriteLogFile("DirectoryCopy.Exception." + ex.Message);
                bRet = false;
            }
            return bRet;
        }
        #endregion 

        #region 디렉토리 복사 (하위폴더의 파일은 폴더생성 없이 그대로 복사)
        /// <summary>
        /// 디렉토리 복사 (하위폴더의 파일은 폴더생성 없이 그대로 복사)
        /// </summary>
        /// <param name="sSrcPath"></param>
        /// <param name="sDstPath"></param>
        /// <param name="sBackPath"></param>
        /// <param name="bDelete"></param>
        public void DirectorySubCopy(string sSrcPath, string sDstPath, string sBackPath, bool bDelete)
        {
            bool bRet = false;

            try
            {
                if (Directory.Exists(sDstPath) == false) Directory.CreateDirectory(sDstPath);
                if (sBackPath.Length > 0 && Directory.Exists(sBackPath) == false) Directory.CreateDirectory(sBackPath);

                DirectoryInfo di = new DirectoryInfo(sSrcPath);
                if (di.Exists)
                {
                    foreach (FileInfo fi in di.GetFiles())
                    {
                        bRet = FileCopy(fi.Name, sSrcPath, sDstPath, sBackPath, bDelete);
                        if (bRet == false) WriteLogFile("frmPosStart_DirectorySubCopy.GetFiles fail -> " + fi.Name);
                    }

                    foreach (DirectoryInfo fi in di.GetDirectories())
                    {
                        //DirectorySubCopy(sSrcPath + fi.Name + @"\", sDstPath + fi.Name + @"\", sBackPath.Length == 0 ? "" : sBackPath + fi.Name + @"\", bDelete);
                        DirectorySubCopy(sSrcPath + fi.Name + @"\", sDstPath, sBackPath.Length == 0 ? "" : sBackPath + fi.Name + @"\", bDelete);
                        try
                        {
                            if (bDelete == true) Directory.Delete(sSrcPath + fi.Name);
                        }
                        catch(Exception ex)
                        {
                            WriteLogFile("frmPosStart_DirectorySubCopy.GetDirectories fail -> " + fi.Name);
                            WriteLogFile("Directory Delete Exception in DirectorySubCopy Method - " + ex.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLogFile("DirectoryCopy.Exception." + ex.Message);
            }
        }
        #endregion 

        #region 폴더의 특정이름으로 시작하는 파일 삭제
        /// <summary>
        /// 폴더의 특정이름으로 시작하는 파일 삭제
        /// </summary>
        /// <param name="sFullPath"></param>
        /// <param name="sDeleteFileName"></param>
        private void DirectoryFileDelete(string sFullPath, string sDeleteFileName)
        {
            try
            {
                string[] fFilePath = Directory.GetFiles(sFullPath);
                foreach (string fFileName in fFilePath)
                {
                    if (fFileName.Contains(sDeleteFileName) == true)
                    {
                        File.Delete(fFileName);
                    }
                }

            }
            catch (Exception ex)
            {
                //#15993 PB 강동역_환경설정 세팅 변경된 원인파악 요청 start
                //기존
                //WriteLogFile("DirectoryFileDelete.Exception." + ex.Message);
                //변경
                WriteLogFile("DirectoryFileDelete.Exception. [PATH:" + sFullPath + ", FILENAME: " + sDeleteFileName + "]" + ex.Message);
                //#15993 PB 강동역_환경설정 세팅 변경된 원인파악 요청 end
            }
        }
        #endregion 

        #region DLL, OCX 등록 처리
        /// <summary>
        /// DLL, OCX 등록 처리
        /// </summary>
        private bool DllRegSvr32(string sPath)
        {
            try
            {
                DirectoryInfo di = new DirectoryInfo(sPath);
                if (di.Exists)
                {
                    foreach (FileInfo fi in di.GetFiles())
                    {
                        string sFileName = fi.Name;

                        if (sFileName.ToUpper().Trim() == "XCTRANSACTION2.DLL") continue;

                        if (sFileName.Substring(sFileName.Length - 4, 4).ToUpper() == ".OCX" || sFileName.Substring(sFileName.Length - 4, 4).ToUpper() == ".DLL" )
                            Process.Start("regsvr32.exe", "/s \"" + sPath + @"\" + sFileName + "\"");

                        //string aaa = "regsvr32.exe /s \"" + sPath + @"\" + sFileName + "\"";
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                WriteLogFile("DllRegSvr32.Exception." + ex.Message);
            }

            return false;
        }

        // grayber@20180115 ADODB.DLL 추가 start
        private bool DLLGacutil(string sPath)
        {
            bool bRes = false;
            try
            {
                // grayber@20180115 명령창 나오지 않도록 개선 start - 명령창이 출력되지 않도록 개선
                // 기존
                // Process.Start(sPath + @"\gacutil.exe", "/i adodb.dll");
                
                // 변경
                ProcessStartInfo psi = new ProcessStartInfo(sPath + @"\gacutil.exe", "/f /i " + sPath + @"\adodb.dll");
                psi.UseShellExecute = false;
                psi.CreateNoWindow = true;
                var psRes = Process.Start(psi);
                
                if (psRes.ExitCode != 0)
                {
                    WriteLogFile(string.Format("DLLGacutil. adodb.dll exitCode: {0}", psRes.ExitCode)); // DEBUG 용 코드
                }
                else { bRes = true; }
                // grayber@20180115 명령창 나오지 않도록 개선 end
            }
            catch(Exception ex)
            {
                WriteLogFile("DLLGacutil.Exception." + ex.Message);
            }

            return bRes;
        }

        // grayber@20180115 ADODB>DLL 추가 end
        private string GetAppSetting(string strKey, string sDefault)
        {
            string strValue = "";

            try
            {
                strValue = System.Configuration.ConfigurationManager.AppSettings[strKey];
            }
            catch { }

            if (strValue == null || strValue == "") strValue = sDefault;

            return strValue;
        }
        #endregion 

        #region 로그파일 저장
        /// <summary>
        /// 로그파일 저장
        /// </summary>
        /// <param name="sFileData"></param>
        /// <returns></returns>
        public bool WriteLogFile(string sFileData)
        {
            bool bRet = false;
            try
            {
                // 현재 디렉토리
                DirectoryInfo directories = Directory.GetParent(Directory.GetCurrentDirectory());
                //
                string sFileName = directories.FullName + @"\LOG\PosStart" + DateTime.Now.ToString("yyMMdd") + ".log";

                FileStream fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);

                try
                {
                    sw.BaseStream.Seek(0, SeekOrigin.End);

                    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + sFileData);
                    sw.Flush();

                    bRet = true;
                }
                catch
                {

                }
                finally
                {
                    sw.Close();
                    fs.Close();
                }
            }
            catch
            {
                return false;
            }
            return bRet;
        }
        #endregion 

        #region 상태 진행바
        /// <summary>
        /// 상태 진행바
        /// </summary>
        /// <param name="iValue"></param>
        /// <param name="iMaxValue"></param>
        private void SetProgreeBar(int iValue, int iMaxValue)
        {
            try
            {
                double nPercent = ((double)iValue / (double)iMaxValue) * 100;

                pbWork.Visible = true;
                pbWork.Minimum = 0;
                pbWork.Maximum = 100;
                pbWork.Value = (int)Math.Round(nPercent, 0, MidpointRounding.AwayFromZero);
                pbWork.Update();

                lblCount.Visible = true;
                lblCount.Text = "POS program check . . . (" + iValue.ToString() + "/" + iMaxValue.ToString() + ") " + Math.Round(nPercent, 0, MidpointRounding.AwayFromZero).ToString() + " %";
                lblCount.Update();

                //System.Threading.Thread.Sleep(300);
                Application.DoEvents();
            }
            catch 
            {
                return;
            }
        }
        #endregion

        //#15993 PB 강동역_환경설정 세팅 변경된 원인파악 요청 start
        /// <summary>
        /// UnnecessaryExeFileDelete
        /// </summary>
        public bool UnnecessaryExeFileDelete() 
        {
            bool bRet = false;

            try
            {
                // 바탕화면에 구포스LOGIN 삭제 
                string sDeskTopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\";
                if (Directory.Exists(sDeskTopPath))
                {
                    DirectoryFileDelete(sDeskTopPath, "LOGIN.exe");
                }

                // 구포스 폴더에 아래 실행파일 삭제
                string sOldPosSrcPath = @"C:\SPCPOS\EXE\";
                if (Directory.Exists(sOldPosSrcPath))
                {
                    DirectoryFileDelete(sOldPosSrcPath, "InfraDownloader.exe");
                    DirectoryFileDelete(sOldPosSrcPath, "InfraInstaller.exe");
                    DirectoryFileDelete(sOldPosSrcPath, "NewPosInstaller.exe");
                }

                // 구포스 폴더에 PLOGIN 백업하고 기존파일 삭제
                DirectoryInfo di = new DirectoryInfo(sOldPosSrcPath);
                if (di.Exists)
                {
                    foreach (FileInfo fi in di.GetFiles())
                    {
                        if (fi.Name == "PLOGIN.exe")
                        {
                            File.Move(sOldPosSrcPath + "\\" + fi.Name, sOldPosSrcPath + "\\" + "back_" + fi.Name);   // 기존파일 이동 처리

                            fi.Delete();
                        }
                    }
                }

                // 차세대 폴더에 아래 실행파일 삭제 
                DirectoryInfo NewPosdirParent = Directory.GetParent(Directory.GetCurrentDirectory()); // 현재 디렉토리 
                string sNewPosSrcPath = NewPosdirParent.FullName + @"\BIN\"; // 대상 폴더 
                if (Directory.Exists(sNewPosSrcPath))
                {
                    DirectoryFileDelete(sNewPosSrcPath, "InfraDownloader.exe");
                    DirectoryFileDelete(sNewPosSrcPath, "InfraInstaller.exe");
                    DirectoryFileDelete(sNewPosSrcPath, "NewPosInstaller.exe");
                }


                bRet = true;
            }
            catch (Exception ex)
            {
                WriteLogFile("UnnecessaryExeFileDelete.Exception. " + ex.Message);
                bRet = false;
            }

            return bRet;
        }
        //#15993 PB 강동역_환경설정 세팅 변경된 원인파악 요청 end
    }
}
