<?xml version='1.0'?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">

  <!-- This is how we include wxi files -->
  <?include "parameters.wxi" ?>

  <!--
    Id="*" is to enable upgrading. * means that the product ID will be autogenerated on each build.
    Name is made of localized product name and version number.
  -->
  <Product Id="*" Name="!(loc.ProductName) v$(var.DisplayVersionNumber)" Language="!(loc.LANG)"
          Version="$(var.VersionNumber)" Manufacturer="!(loc.ManufacturerName)" UpgradeCode="$(var.UpgradeCode)">

    <!--
      Define the minimum supported installer version (2.0).
      The install should be done for the whole machine not just the current user
    -->
    <Package InstallerVersion="200" InstallPrivileges="elevated"
             Compressed="yes" InstallScope="perMachine" />

    <!--
      Create property references for the well known SIDs of the 
      accounts we want to restrict for the project location folder
    -->
    <PropertyRef Id="WIX_ACCOUNT_LOCALSYSTEM" />
    <PropertyRef Id="WIX_ACCOUNT_ADMINISTRATORS" />
    <PropertyRef Id="WIX_ACCOUNT_USERS" />

    <Media Id="1" Cabinet="ChefClient.cab" EmbedCab="yes" CompressionLevel="high" />

    <!--
    Take advantage of Windows Installer 5.0 feature (if available) to disable 
    checkpointing and other costings that take significant amounts of time 
    ref: https://msdn.microsoft.com/en-us/library/windows/desktop/dd408005(v=vs.85).aspx
    -->
    <Property Id="MSIFASTINSTALL" Value="7" />

    <Property Id="CHEF_SERVICE_OPTIONS_RADIO_BUTTON_GROUP" Value="None" />

    <!--
      Uncomment launch condition below to check for minimum OS
      601 = Windows 7/Server 2008R2.
    -->
    <!-- Condition Message="!(loc.MinimumOSVersionMessage)">
      <![CDATA[Installed OR VersionNT >= 601]]>
    </Condition -->

    <!-- We always do Major upgrades -->
    <MajorUpgrade DowngradeErrorMessage="!(loc.DowngradeErrorMessage)" />


    <!--
      If fastmsi is set, custom actions will be invoked during install to unzip
      project files, and during uninstall to remove the project folder
    -->
    <% if fastmsi %>
    <SetProperty Id="FastUnzip"
                 Value="FASTZIPDIR=[INSTALLLOCATION];FASTZIPAPPNAME=$(var.ProjectLocationDir)"
                 Sequence="execute"
                 Before="FastUnzip" />

    <CustomAction Id="FastUnzip"
                  BinaryKey="CustomActionFastMsiDLL"
                  DllEntry="FastUnzip"
                  Execute="deferred"
                  Impersonate="no"
                  Return="check" />

    <Binary Id="CustomActionFastMsiDLL"
            SourceFile="CustomActionFastMsi.CA.dll" />

    <CustomAction Id="Cleanup"
                  Directory="INSTALLLOCATION"
                  ExeCommand="cmd /C &quot;rd /S /Q $(var.ProjectLocationDir)&quot;"
                  Execute="deferred"
                  Impersonate="no"
                  Return="ignore" />

    <CustomAction Id="CreateChefClientScheduledTask"
                  Directory="TARGETDIR"
                  ExeCommand="&quot;[SystemFolder]SCHTASKS.EXE&quot; /CREATE /TN &quot;chef-client&quot; /SC &quot;MINUTE&quot; /MO &quot;30&quot; /F /TR &quot;cmd /c \&quot;[EMBEDDEDBIN]ruby.exe [PROJECTLOCATIONBIN]chef-client -L [CONFIGLOCATION]chef-client.log -c [CONFIGLOCATION]client.rb\&quot;&quot; /RU &quot;NT Authority\System&quot; /RP /RL &quot;HIGHEST&quot;"
                  Execute="deferred"
                  Impersonate="no"
                  Return="check" />

    <CustomAction Id="RemoveChefClientScheduledTask"
                  Directory="TARGETDIR"
                  ExeCommand="&quot;[SystemFolder]SCHTASKS.EXE&quot; /DELETE /TN &quot;chef-client&quot; /F"
                  Execute="deferred"
                  Impersonate="no"
                  Return="ignore" />

    <CustomAction Id="RemoveChefClientService"
                  Directory="TARGETDIR"
                  ExeCommand="&quot;[SystemFolder]SC.EXE&quot; DELETE &quot;chef-client&quot;"
                  Execute="deferred"
                  Impersonate="no"
                  Return="ignore" />

    <InstallExecuteSequence>
      <Custom Action="FastUnzip" After="InstallFiles">NOT Installed OR REINSTALL</Custom>
      <Custom Action="Cleanup" After="RemoveFiles">REMOVE~="ALL"</Custom>

      <Custom Action="CreateChefClientScheduledTask" After="InstallFiles">
        <![CDATA[&ChefSchTaskFeature=3]]>
      </Custom>

      <Custom Action="RemoveChefClientScheduledTask" Before="RemoveFiles">
        <![CDATA[(Installed AND (&NoneFeature=3 OR &ChefServiceFeature=3)) OR (REMOVE="ALL")]]>
      </Custom>

      <Custom Action="RemoveChefClientService" Before="RemoveFiles">
        <![CDATA[Installed AND (&NoneFeature=3 OR &ChefSchTaskFeature=3) OR (REMOVE="ALL")]]>
      </Custom>
    </InstallExecuteSequence>

    <UI>
      <ProgressText Action="FastUnzip">!(loc.FileExtractionProgress)</ProgressText>
    </UI>
    <% end %>

    <Directory Id="TARGETDIR" Name="SourceDir">
      <Directory Id="WindowsVolume">
        <!-- Service needs chef directory to be present. -->
        <Directory Id="CONFIGLOCATION" Name="chef">
          <Component Id="CONFIGLOCATIONDIR" Guid="{F66F6394-51A4-4C5D-908B-E55584473436}" >
            <CreateFolder Directory="CONFIGLOCATION" />
          </Component>
        </Directory>
        <Directory Id="INSTALLLOCATION" Name="opscode">
          <Directory Id="PROJECTLOCATION" Name="$(var.ProjectLocationDir)" >
            <Component Id="ProjectLocationPermissions" Guid="{75f50556-efae-4ede-beb2-a2c9b1a4d43f}" >
              <!--
                Windows client SKUs give the Authenticated Users group modify rights
                to new folders created. We ONLY want the local system account and any administrator to have that right to protect non admin users from injecting code that could be executed by a service running as SYSTEM
              -->
              <CreateFolder>
                <Permission User="[WIX_ACCOUNT_LOCALSYSTEM]" GenericAll="yes"/>
                <Permission User="[WIX_ACCOUNT_ADMINISTRATORS]" GenericAll="yes"/>
                <Permission User="[WIX_ACCOUNT_USERS]" GenericRead="yes" GenericExecute="yes"/>
              </CreateFolder>
            </Component>
            <Directory Id="PROJECTLOCATIONBIN" Name="bin" >
              <Component Id="ChefClientPath" Guid="{7F663F88-55A2-4E20-82BF-8BD2E60BB83A}" >
                <Environment Id="ClientPathEnvironment"
                             Name="PATH" Action="set" Part="last" System="yes" Value="[PROJECTLOCATIONBIN]" />
              </Component>
            </Directory>
            <Directory Id="PSMODULES" Name="modules" >
              <Component Id="ChefPSModulePath" Guid="{357DA654-F02E-430A-9EA6-A10554E3EF38}" >
                <Environment Id="ChefPSModulePathEnvironment"
                             Name="PSModulePath" Action="set" Part="last" System="yes" Value="[PSMODULES]" />
              </Component>
            </Directory>
            <Directory Id="EMBEDDED" Name="embedded" >
              <Directory Id="EMBEDDEDBIN" Name="bin" >
                <Component Id="ChefClientService" Guid="{69B2D8BE-4A47-4BE3-AEE8-83FAEB6E2FAF}" >
                  <File Id="RubyExecutable" Source="$(var.ProjectSourceDir)\embedded\bin\ruby.exe" KeyPath="yes" />
                  <ServiceInstall Name="chef-client" Type="ownProcess"
                                  Start="auto" Vital="yes" ErrorControl="ignore"
                                  Arguments="[PROJECTLOCATION]bin\chef-windows-service"
                                  DisplayName="!(loc.ServiceDisplayName)"
                                  Description="!(loc.ServiceDescription)">
                      <ServiceDependency Id="Winmgmt" />
                      <ServiceConfig DelayedAutoStart="yes" OnInstall="yes" />
                  </ServiceInstall>
                  <ServiceControl Id="ControlChefClientService" Name="chef-client"
                                  Remove="both" Stop="both" Wait="yes" />
                </Component>
                <Component Id="ChefClientLog" Guid="{8e492d59-3a0c-43fd-b889-e35dfa33da91}">
                    <util:EventSource xmlns:util="http://schemas.microsoft.com/wix/UtilExtension"
                        Name="Chef" Log="Application"
                        EventMessageFile="[PROJECTLOCATION]$(var.ChefLogDllPath)"
                        />
                </Component>
              </Directory>
            </Directory>
          </Directory>
        </Directory>
        <Directory Id="ChefSchTaskFeatureTempDir">
          <Component Id="ChefSchTask" Guid="{7f9f917a-952c-41d8-baa1-037269eecb50}">
            <CreateFolder />
          </Component>
        </Directory>
        <Directory Id="NoneFeatureTempDir">
          <Component Id="None" Guid="{d8f3eba5-cecb-436c-a4ef-540dba3c5ccf}">
            <CreateFolder />
          </Component>
        </Directory>
      </Directory>
    </Directory>

    <!-- Set the components defined in our fragment files that will be used for our feature  -->
    <Feature Id="ChefClientFeature" Title="!(loc.FeatureMainName)" Absent="disallow" AllowAdvertise="no" Level="1" ConfigurableDirectory="INSTALLLOCATION">
      <ComponentGroupRef Id="ProjectDir" />
      <ComponentRef Id="ProjectLocationPermissions" />
      <ComponentRef Id="ChefClientPath" />
      <ComponentRef Id="CONFIGLOCATIONDIR" />
      <ComponentRef Id="ChefClientLog" />
    </Feature>

    <Feature Id="ChefPSModuleFeature" Title="!(loc.FeaturePSModuleName)" Level="1000" AllowAdvertise="no">
      <ComponentRef Id="ChefPSModulePath" />
    </Feature>

    <Feature Id="ChefUnattendedExecutionOptions" Title="Chef Unattended Execution Options" Level="1000" AllowAdvertise="no">
      <Feature Id="ChefSchTaskFeature" Title="!(loc.FeatureSchTaskName)" Level="1000" AllowAdvertise="no" Display="hidden">
        <!-- Here, CustomAction will get executed and scheduled task for chef-client will get created -->

        <!-- This is an empty component to keep track of the feature -->
        <ComponentRef Id="ChefSchTask" />
      </Feature>

      <Feature Id="ChefServiceFeature" Title="!(loc.FeatureServiceName)" Level="1000" AllowAdvertise="no" Display="hidden">
        <ComponentRef Id="ChefClientService" />
      </Feature>

      <Feature Id="NoneFeature" Title="None" Level="1000" AllowAdvertise="no" Display="hidden">
        <!-- Do Nothing -->

        <!-- This is an empty component to keep track of the feature -->
        <ComponentRef Id="None" />
      </Feature>
    </Feature>

    <!--
      TODO:

      * create initial Client config? ie C:\chef\client.rb?
      * optionally install extra tools?  ie git?

    -->

    <!--
      UI Stuff
    -->
    <Icon Id="oc.ico" SourceFile="Resources\assets\oc_16x16.ico"/>
    <Property Id="ARPPRODUCTICON" Value="oc.ico" />
    <Property Id="ARPHELPLINK" Value="https://www.chef.io/support/" />
    <Property Id="WIXUI_INSTALLDIR" Value="INSTALLLOCATION" />

    <UIRef Id="ChefClientUI_InstallDir"/>
    <UI Id="ChefClientUI_InstallDir">
      <!-- WixUI_FeatureTree module's code embedded and modified here as per the requirement -->
      <TextStyle Id="WixUI_Font_Normal_White" FaceName="Tahoma" Size="8" Red="255" Green="255" Blue="255" />
      <TextStyle Id="WixUI_Font_Bigger_White" FaceName="Tahoma" Size="12" Red="255" Green="255" Blue="255" />
      <TextStyle Id="WixUI_Font_Title_White" FaceName="Tahoma" Size="9" Bold="yes" Red="255" Green="255" Blue="255" />
      <TextStyle Id="WixUI_Font_Normal" FaceName="Tahoma" Size="8" />
      <TextStyle Id="WixUI_Font_Bigger" FaceName="Tahoma" Size="12" />
      <TextStyle Id="WixUI_Font_Title" FaceName="Tahoma" Size="9" Bold="yes" />
      <TextStyle Id="WixUI_Font_Msg" FaceName="Tahoma" Size="9" />

      <Property Id="DefaultUIFont" Value="WixUI_Font_Normal" />
      <Property Id="WixUI_Mode" Value="FeatureTree" />

      <DialogRef Id="ErrorDlg" />
      <DialogRef Id="FatalError" />
      <DialogRef Id="FilesInUse" />
      <DialogRef Id="MsiRMFilesInUse" />
      <DialogRef Id="PrepareDlg" />
      <DialogRef Id="ProgressDlg" />
      <DialogRef Id="ResumeDlg" />
      <DialogRef Id="UserExit" />

      <Publish Dialog="ExitDialog" Control="Finish" Event="EndDialog" Value="Return" Order="999">1</Publish>

      <Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="LicenseAgreementDlg">NOT Installed</Publish>
      <Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg">Installed AND PATCH</Publish>

      <Publish Dialog="LicenseAgreementDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg">1</Publish>
      <Publish Dialog="LicenseAgreementDlg" Control="Next" Event="NewDialog" Value="CustomizeDlg">LicenseAccepted = "1"</Publish>

      <Publish Dialog="CustomizeDlg" Control="Back" Event="NewDialog" Value="MaintenanceTypeDlg" Order="1">Installed</Publish>
      <Publish Dialog="CustomizeDlg" Control="Back" Event="NewDialog" Value="LicenseAgreementDlg" Order="2">NOT Installed</Publish>

      <Publish Dialog="CustomizeDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg"><![CDATA[((NOT &ChefUnattendedExecutionOptions=3) AND NOT ((?ChefSchTask=3) OR (?ChefClientService=3) OR (?None=3)))]]></Publish>

      <Publish Dialog="CustomizeDlg" Control="Next" Event="NewDialog" Value="ChefUnattendedExecutionOptionsSelectionDlg"><![CDATA[((&ChefUnattendedExecutionOptions=3) OR (?ChefSchTask=3 OR ?ChefClientService=3 OR ?None=3))]]></Publish>

      <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="CustomizeDlg" Order="1"><![CDATA[NOT &ChefUnattendedExecutionOptions=3]]> AND (NOT Installed OR WixUI_InstallMode = "Change")</Publish>
      <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="ChefUnattendedExecutionOptionsSelectionDlg" Order="1"><![CDATA[&ChefUnattendedExecutionOptions=3]]> AND (NOT Installed OR WixUI_InstallMode = "Change")</Publish>
      <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="MaintenanceTypeDlg" Order="2">Installed AND NOT PATCH</Publish>
      <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg" Order="3">Installed AND PATCH</Publish>

      <Publish Dialog="MaintenanceWelcomeDlg" Control="Next" Event="NewDialog" Value="MaintenanceTypeDlg">1</Publish>

      <Publish Dialog="MaintenanceTypeDlg" Control="ChangeButton" Event="NewDialog" Value="CustomizeDlg">1</Publish>
      <Publish Dialog="MaintenanceTypeDlg" Control="RepairButton" Event="NewDialog" Value="VerifyReadyDlg">1</Publish>
      <Publish Dialog="MaintenanceTypeDlg" Control="RemoveButton" Event="NewDialog" Value="VerifyReadyDlg">1</Publish>
      <Publish Dialog="MaintenanceTypeDlg" Control="Back" Event="NewDialog" Value="MaintenanceWelcomeDlg">1</Publish>

      <Dialog Id ="ChefUnattendedExecutionOptionsSelectionDlg" Width ="370" Height ="270" Title ="!(loc.ProductName) v$(var.DisplayVersionNumber) Setup" NoMinimize ="no">
        <Control Id="BannerBitmap" Type="Bitmap" X="0" Y="0" Width="370" Height="44" TabSkip="no" Text="!(loc.CustomizeDlgBannerBitmap)" />
        <Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
        <Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />
        <Control Id="Title" Type="Text" X="15" Y="6" Width="210" Height="15" Transparent="yes" NoPrefix="yes" Text="!(loc.CustomizeDlgTitle)" />
        <Control Id="Description" Type="Text" X="25" Y="23" Width="280" Height="15" Transparent="yes" NoPrefix="yes" Text="!(loc.CustomizeDlgDescription)" />
        <Control Id="TextMsg" Type="Text" X="25" Y="55" Width="320" Height="20" Text="!(loc.CustomizeDlgTextMsg)" />

        <Control Id="LeftBox" Type="GroupBox" X="25" Y="81" Width="175" Height="118" />
        <Control Id="TextTitle" Type="Text" X="30" Y="100" Width="169" Height="20" Text="{\WixUI_Font_Title}!(loc.CustomizeDlgTextTitle)" />
        <Control Id="OptionsRadioGroup" Type="RadioButtonGroup" Property="CHEF_SERVICE_OPTIONS_RADIO_BUTTON_GROUP" Height="80" Width="140" X="35" Y="110">
          <RadioButtonGroup Property="CHEF_SERVICE_OPTIONS_RADIO_BUTTON_GROUP">
            <RadioButton Value="SchTask" Text="!(loc.CustomizeDlgFirstRadioButtonText)" Height="17" Width="140" X="0" Y="10" />
            <RadioButton Value="Service" Text="!(loc.CustomizeDlgSecondRadioButtonText)" Height="17" Width="140" X="0" Y="35" />
            <RadioButton Value="None" Text="!(loc.CustomizeDlgThirdRadioButtonText)" Height="17" Width="140" X="0" Y="60" />
          </RadioButtonGroup>
        </Control>

        <Control Id="RightBox" Type="GroupBox" X="210" Y="81" Width="150" Height="118" />
        <Control Id="OptionsMsg" Type="Text" X="214" Y="100" Width="146" Height="80" Text="{\WixUI_Font_Msg}!(loc.CustomizeDlgOptionsMsg)" />

        <Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17" Default="no" Text="Back">
          <Publish Event="NewDialog" Value="CustomizeDlg">1</Publish>
        </Control>
        <Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17" Default="yes" Text="Next">
          <Publish Event="AddLocal" Value="ChefSchTaskFeature">CHEF_SERVICE_OPTIONS_RADIO_BUTTON_GROUP = "SchTask"</Publish>
          <Publish Event="AddLocal" Value="ChefServiceFeature">CHEF_SERVICE_OPTIONS_RADIO_BUTTON_GROUP = "Service"</Publish>
          <Publish Event="AddLocal" Value="NoneFeature">CHEF_SERVICE_OPTIONS_RADIO_BUTTON_GROUP = "None"</Publish>
          <Publish Event="NewDialog" Value="VerifyReadyDlg">1</Publish>
        </Control>
        <Control Id="Cancel" Type="PushButton" X="304" Y="243" Width="56" Height="17" Default="no" Text="Cancel" Cancel="yes">
          <Publish Event="SpawnDialog" Value="CancelDlg">1</Publish>
        </Control>
      </Dialog>
    </UI>

    <UIRef Id="WixUI_Common" />

    <WixVariable Id="WixUILicenseRtf" Value="Resources\assets\LICENSE.rtf" />
    <WixVariable Id="WixUIDialogBmp" Value="Resources\assets\dialog_background.bmp" />
    <WixVariable Id="WixUIBannerBmp" Value="Resources\assets\banner_background.bmp" />

    <WixVariable Id="WixUIExclamationIco" Value="Resources\assets\oc_32x32.ico" />
    <WixVariable Id="WixUIInfoIco" Value="Resources\assets\oc_32x32.ico" />
    <WixVariable Id="WixUINewIco" Value="Resources\assets\oc_16x16.ico" />
    <WixVariable Id="WixUIUpIco" Value="Resources\assets\oc_16x16.ico" />

  </Product>
</Wix>
