param([string]$webAppUrl)
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) 
{
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
if(-not($webAppUrl))
{	
    $webAppUrl = Read-Host "Web Application URL"
}

$farm=Get-SPFarm
$farmId=$farm.ID

$spWeb = Get-SPWeb $webAppUrl -ErrorAction SilentlyContinue
if(-not($spWeb)){
    Write-Error -Message "Not find the root site $webAppUrl" -ErrorAction Continue
    Read-Host -Prompt "Press Enter to quit..."
    exit 0
}
$spDocumentLibrary = $spWeb.Lists.EnsureSiteAssetsLibrary()
$localDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
$targetFolder="$localDir\sbForms"

function Import-OSCFolder
{
	param 
	(
		[Parameter(Mandatory=$true,Position=2)]
		[string]$Path
	)
	
	#verify if the path is valid
	If(Test-Path -Path $Path)
	{
		#Get the folder
		$Fol = Get-Item -Path $Path 
		If($Fol.PSIsContainer)
		{
			$SPFol = $spWeb.GetFolder($spDocumentLibrary.RootFolder.ServerRelativeUrl +"/"+ $Fol.Name )
			If($SPFol.Exists -eq "True")
			{
				Write-Warning "There is a folder existing on site $siteUrl."
                $SPFol=$SPFol.Item
			}
			Else
			{
				#Import the folder to site library.
				$SPFol = $spDocumentLibrary.AddItem("",[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$Fol.Name) 
				$SPFol.Update()
			}
				
			SubFolder  $path $SPFol
					
			Write-Host "Import '$Path' folder to site $siteurl successfully."
		}
		Else
		{
			Write-Error "The object is not a folder."
		}
	}
	Else 
	{
		Write-Error "Invalid path,try again."
	}	
}

function SubFolder($Folder,$SPFol)
{
	#Import the folder and subfolders to site library.
	$SPFolder = $spWeb.GetFolder($SPFol.Folder.ServerRelativeUrl)
	$Objects = Get-ChildItem -Path $Folder 
	Foreach($obj in $Objects)
	{
		If($obj.PSIsContainer)
		{	
			$SubFolder = $spWeb.GetFolder($SPFolder.ServerRelativeUrl +"/"+ $obj.Name)
            If( $SubFolder.Exists -eq "True"){
			    $SubFolder=$SubFolder.Item
            } else {
                $SubFolder = $spDocumentLibrary.AddItem($SPFolder.ServerRelativeUrl,[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$obj.Name)
			    $SubFolder.Update()
            }
			$Fullname = $obj.FullName
			SubFolder  $Fullname $SubFolder
			
		}
		Else
		{	
			$fileStream = ([System.IO.FileInfo]$obj).OpenRead() 
			$FolderObj = $spWeb.GetFolder($SPFolder.ServerRelativeUrl)
			$SpFile = $FolderObj.Files.Add($FolderObj.Url + "/"+$obj.Name, $fileStream, $true)			
			$spItem = $SpFile.Item
		}
	}

}

Write-Host "Uploading skybow Modern Forms resources to Site Assets library..."

Import-OSCFolder -path $targetFolder
$spWeb.Dispose();

Read-Host -Prompt "Press Enter to quit..."
exit 0

