client_id = itsm.getParameter('client_id')

client_secret = itsm.getParameter('client_secret')

refresh_token = itsm.getParameter('refresh_token')

source_path_to_upload = itsm.getParameter('source_path_to_upload')

import os
import shutil
from subprocess import Popen, PIPE
import ctypes

if not os.path.exists(source_path):
    raise Exception("given source path doesn't exists on this machine")

class disable_file_system_redirection:
    _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
    _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
    def __enter__(self):
        self.old_value = ctypes.c_long()
        self.success = self._disable(ctypes.byref(self.old_value))
    def __exit__(self, type, value, traceback):
        if self.success:
            self._revert(self.old_value)

class ExecutionPolicy:
    def __enter__(self):
        with disable_file_system_redirection():
            #getting current executionpolicy
            self.old_policy = os.popen('powershell "Get-ExecutionPolicy"').read().strip()
            #setting execution policy to RemoteSigned
            os.popen('powershell "Set-ExecutionPolicy RemoteSigned"').read()
    def __exit__(self, type, value, traceback):
        with disable_file_system_redirection():
            #setting execution policy back to previous policy
            os.popen('powershell "Set-ExecutionPolicy %s"'%(self.old_policy)).read()

def ecmd(command):   
    with disable_file_system_redirection():
        obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
    out, err = obj.communicate()
    ret=obj.returncode
    if ret==0:
        if out:
            print(out.strip())
        else:
            print("Successfully uploaded the file")
            print(ret)
    else:
        if err:
            print("an error occurred: %s"%(err.strip()))
        else:
            print("something went wrong. returncode: %s"%(ret))

def write_and_Execute(PS, file):
    ps_name='powershell_file.ps1'
    ps_path=os.path.join(os.environ['TEMP'], ps_name)
    with open(ps_path, 'wb') as wr:
        wr.write(GDuploadPS)
    with ExecutionPolicy():
        ecmd('powershell "%s"'%ps_path)
    os.remove(ps_path)
    


GDuploadPS = r"""
$ClientID = "%s"
$ClientSecret = "%s"
$RefreshToken = "%s"

$params = @{
    Uri = 'https://accounts.google.com/o/oauth2/token'
    Body = @(
        "refresh_token=$RefreshToken", 
        "client_id=$ClientID",        
        "client_secret=$ClientSecret", 
        "grant_type=refresh_token"
    ) -join '&'
    Method = 'Post'
    ContentType = 'application/x-www-form-urlencoded'
}
$accessToken = (Invoke-RestMethod @params).access_token

$SourceFile = "%s"

$sourceItem = Get-Item $sourceFile
$sourceBase64 = [Convert]::ToBase64String([IO.File]::ReadAllBytes($sourceItem.FullName))
$sourceMime = [System.Web.MimeMapping]::GetMimeMapping($sourceItem.FullName)

$supportsTeamDrives = 'false'

$uploadMetadata = @{
    originalFilename = $sourceItem.Name
    name = $sourceItem.Name
    description = $sourceItem.VersionInfo.FileDescription
}

$uploadBody = @"
--boundary
Content-Type: application/json; charset=UTF-8

$($uploadMetadata | ConvertTo-Json)

--boundary
Content-Transfer-Encoding: base64
Content-Type: $sourceMime

$sourceBase64
--boundary--
"@

$uploadHeaders = @{
    "Authorization" = "Bearer $accessToken"
    "Content-Type" = 'multipart/related; boundary=boundary'
    "Content-Length" = $uploadBody.Length
}

$response = Invoke-RestMethod -Uri "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsTeamDrives=$supportsTeamDrives" -Method Post -Headers $uploadHeaders -Body $uploadBody
"""


if os.path.isfile(source_path):
    GDuploadPS = GDuploadPS%(client_id,client_secret,refresh_token,source_path)
    write_and_Execute(GDuploadPS, source_path)
else:
    Save_path = os.environ['TEMP'] + '\%s'%(os.path.basename(source_path))
    zipPath = shutil.make_archive(Save_path, 'zip', source_path)
    GDuploadPS = GDuploadPS%(client_id,client_secret,refresh_token, zipPath)
    write_and_Execute(GDuploadPS, zipPath)
    os.remove(zipPath)
    