###################################
# This script retrieves all files identified for use with JHA and 
# bundles them in a zip file for distribution.
###################################
#REQUIREMENTS
#--Outbound access to the internet on https/443
#--The $paramFile var defined pointing to a paramter file that contains
#  necessary variables that need to have values that change; in initial POC those are like so:
#--To keep source and destination in sync, the destination should be purged by some other means 
#  prior to execution since this relies on azcopy COPY command (files in dst that don't exist in source will not be deleted from dst)
###################################
#REVISION HISTORY
#2021.03.19 - kel.mankenberg - Base version
###################################
#RESOURCES
# https://sqlsrv4living.blogspot.com/2020/02/azure-blob-storage-list-and-download.html
# https://www.quora.com/How-do-I-download-content-of-URLs-found-in-a-list-using-Powershell
# http://pvlerick.github.io/2009/03/powershell-script-to-download-a-list-of-files
###################################
#VARIABLES
$dt = $(get-date -format "yyyyMMdd_HHmmss")
$scriptDir = "C:\DITA\scripts\JHA_Resources"
$logDir = ($scriptDir) + "\logs"
$logFileShortName = ($MyInvocation.MyCommand.Name).Replace(".ps1","_$dt.log")
$logFile = "$logDir\" + $logFileShortName
$ListOfFiles = Get-Content -Path ResourceFilesToInclude.txt
$azCopyExePath = "C:\DITA\scripts\azcopy\bin\azcopy_v10\azcopy.exe"
$scriptDir = "C:\DITA\scripts\JHA_Resources"
$logDir = ($scriptDir) + "\logs"
$JHAFilesDir = ($scriptDir) + "\FilesForJHA"
$StorageAcctSasToken = "?sv=2019-12-12&ss=f&srt=sco&sp=rwdlc&se=2026-02-12T01:12:12Z&st=2021-02-11T17:12:12Z&spr=https&sig=fLs1jOyY8N%2Fqs0oo07GQkvjghei8gDP5BT5fFrS%2F0%2FA%3D"
$StorageAcctBaseUrl = "https://zusscgrcprodwebhelp.file.core.windows.net/webhelp/dev"
$srcPath = "resources/"
$ZipFile = "REsources-For-JHA.zip"
$currentScript = $MyInvocation.MyCommand.Path
$myComputer = (gci env:computername).Value
###################################
###################################
#MAKE NO CHANGES BELOW THIS LINE

$error.clear()
$ErrorActionPreference = "Stop"

function currentTime{
    get-date -format "yyyyMMdd_HHmmss"
}
function funcLog($message) {
	(currentTime) + " " + $message | Out-File $logFile -append
}
function funcExitWithError{
	funcLog "=================================="
	funcLog "END EXECUTION - ABNORMAL TERMINATION ($currentScript)"
	"END EXECUTION - ABNORMAL TERMINATION ($currentScript)"
	funcLog "=================================="
	exit 1
}
function funcCreateLogDir{
    if (Test-Path $logdir)
        {
        Start-Sleep -Seconds 0
        }
    else
        {
        mkdir $logdir
        }
}
function funcCreateFilesDir{
    if (Test-Path $JHAFilesDir)
        {
        Start-Sleep -Seconds 0
        }
    else
        {
        mkdir $JHAFilesDir
        }
}
function funcDownloadBlob{
    try{
        $startTime = (Get-Date)
        funcLog "start sync"
        & "$azCopyExePath" cp $srcPath $storageAcctFullUrl --recursive=true --preserve-smb-info=true | Out-File $logFile -Append
        $endTime = (Get-Date)
        funcLog "End sync"
        funcLog "Total upload time: $(($endTime-$startTime).totalseconds) seconds"
    }
    catch{
        Out-File $logFile -InputObject $error -append
        funcExitWithError
    }
    finally{
        funcLog "End funcDownloadBlob function."
    }
}
function funcDownloadFiles{
    try{
        $startTime = (Get-Date)
        funcLog "start sync"
        & "$azCopyExePath" cp $srcPath $storageAcctFullUrl --recursive=true --preserve-smb-info=true | Out-File $logFile -Append
        $endTime = (Get-Date)
        funcLog "End sync"
        funcLog "Total upload time: $(($endTime-$startTime).totalseconds) seconds"
    }
    catch{
        Out-File $logFile -InputObject $error -append
        funcExitWithError
    }
    finally{
        funcLog "End funcDownloadBlob function."
    }
}
function funcEndGraceful{
    funcLog "=================================="
    funcLog "END EXECUTION OF $currentScript on $myComputer"
    funcLog "=================================="
    Get-Content $logFile
}
function funcCleanLogs{
	gci $logDir\*.log | ? {$_.LastWriteTime -lt (get-date).AddDays(-7)} | del -force
}
function funcBeginScript{
    funcLog "=================================="
    funcLog "BEGIN EXECUTION OF $currentScript on $myComputer"
    funcLog "=================================="
}
function funcListFilesToConsole{
    # 1..100 | ForEach-Object { Add-Content -Path .\ResourceFilesToInclude.txt -Value ($StorageAcctBaseUrl + $_. }
    # Get-Content -Path .\ResourceFilesToInclude.txt
    try{
        # $list = Get-Content -Path .\ResourceFilesToInclude.txt
        # foreach ($url in $list) {
        #     $filename = $url.Substring(61, ($url.Length - 61))
        #     $FileToDownload = ($url + $StorageAcctSasToken)
        #     $TargetFile = ($JHAFilesDir + $filename).Replace('/', '\')
        #     # Write-Host $url
        #     # Write-Host $TargetFile
        #     # funcLog "start sync"
        #     & "$azCopyExePath" copy $FileToDownload $TargetFile
        #     funcLog "End sync"
        # }

        & "$azCopyExePath" copy "https://zusscgrcprodwebhelp.file.core.windows.net/webhelp/dev/resources/webhelp-includes/?sv=2019-12-12&ss=f&srt=sco&sp=rwdlc&se=2026-02-12T01:12:12Z&st=2021-02-11T17:12:12Z&spr=https&sig=fLs1jOyY8N%2Fqs0oo07GQkvjghei8gDP5BT5fFrS%2F0%2FA%3D" "C:\DITA\scripts\JHA_Resources\FilesForJHA\resources\" --recursive
    }
    catch{
        Out-File $logFile -InputObject $error -append
        funcExitWithError
    }

    # $list = Get-Content -Path .\ResourceFilesToInclude.txt
    # $clnt = New-Object System.Net.WebClient

    # foreach($url in $list) 
    # { 
    #     #Get the filename 
    #     $filename = [System.IO.Path]::GetFileName($url) 
    #     #Create the output path 
    #     $file = [System.IO.Path]::Combine($pwd.Path, $filename) 
    #     Write-Host -NoNewline "Getting ""$url""... "
    #     #Download the file using the WebClient 
    #     $FileToDownload = ($url + $StorageAcctSasToken)
    #     $clnt.DownloadFile($FileToDownload, $file) 
    #     Write-Host "done." 
    # }
}





function funcMain{
    funcCreateLogDir
    funcCreateFilesDir
    funcBeginScript
    # #funcDownloadBlob
    # funcDownloadFiles
    funcListFilesToConsole
    funcEndGraceful
}




funcMain