#Requires -Version 3.0

function Install-Ola
{
[CmdletBinding(DefaultParameterSetName="Default", SupportsShouldProcess = $true)] 


Param(
	[parameter(Mandatory = $true, ValueFromPipeline = $true)]
	[string]$SqlServer,
    [string]$BackupDir,
    [int]$CleanupTime,
    [string]$Schedule
	)

    BEGIN
    {
        Write-Verbose "Start Loop"

        [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
        [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | out-null

        function PSScriptRoot { $MyInvocation.ScriptName | Split-Path }

        $MaintenanceSolution = "$(PSScriptRoot)\scripts\MaintenanceSolution.sql"

        $script = @()
        [string]$scriptpart

        $fullscript = Get-Content $MaintenanceSolution
        foreach($line in $fullscript)
        {   
            if ($line -ne "GO")
            {
                if ($BackupDir -and $line -match "Specify the backup root directory")
                {
                    $line = $line.Replace("C:\Backup", $BackupDir)
                }
                if ($CleanupTime -and $line -match "Time in hours, after which backup files are deleted")
                {
                    $line = $line.Replace("NULL", $CleanupTime)
                }

                $scriptpart += $line + "`n"
            }
            else
            {
                $properties = @{Scriptpart = $scriptpart}
                $newscript = New-Object PSObject -Property $properties
                $script += $newscript
                $scriptpart = ""
                $newscrpt = $null
            }
        }
    }

    PROCESS
    {
        $out = "Installing Maintenancesolution on server: {0}" -f $SqlServer
        Write-Verbose $out

        $ConnectionString = "Server = $SqlServer ; Database = master; Integrated Security = True;"
        $Connection = New-Object System.Data.SQLClient.SQLConnection 
        $Connection.ConnectionString = $ConnectionString      
        $Connection.Open();
        $Command = New-Object System.Data.SQLClient.SQLCommand 
        $Command.Connection = $Connection


        foreach ($scriptpart in $script)
        {
            $Command.CommandText = $($scriptpart.scriptpart)
            $niks = $Command.ExecuteNonQuery();           
        }
        if ($Schedule)
        {
            $Command.CommandText = get-content $Schedule
            $niks = $Command.ExecuteNonQuery();
        }

        $Connection.Close();            
    }

    END
    {
        Write-Verbose "End Loop"
    }

}


