param (
    [string]$server,
    [string]$token,
    [string]$location,
    [string]$devFolder, 
    [string]$serverIP,  
    [string]$build,
    [string]$type,
    [string]$username,
    [string]$admpass,
    [string]$obslst,
    [string]$obsBuild
)

# Convert the plain-text password to a SecureString
$securePass = ConvertTo-SecureString $admpass -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential($username, $securePass)

# lets get the version of the app we are updating
$pkgFile = "$devFolder\package.json"
$package = Get-Content -Path $pkgFile -Raw | ConvertFrom-Json

$version = "$($package.version)-$($package.admConfig.build -1)"

# Checking to make sure the server is up and online
Write-Output "Checking if $($token) is online to update."
$pingResult = Test-Connection -ComputerName $serverIP -Count 2 -Quiet

if (-not $pingResult) {
    Write-Output "Server $($server) $($serverIP) is NOT reachable. Exiting script."
    exit 1 # Terminate the script with a non-zero exit code
}

Write-Output "Server $($server) ($serverIP) is online."

# get the file name we want to grab

$buildZip = "lstv2-$version.zip"

if (-Not (Test-Path -Path "$($build)\$($buildZip)")) {
    Write-Host "Build is missing from the build folder."
    Write-host $buildZip
    exit
}

Write-Host "---------------Starting the update Process----------------------------------"
Write-Host "File to be copied over is $buildZip"
Write-Host "Coping files to $($server)"
$destination = "\\$($server)\$($location)" -replace ":", "$"
Write-Host $destination
Write-Host "Forcing the removal of the mapped drive."
Get-PSDrive -Name "z" -ErrorAction SilentlyContinue | Remove-PSDrive -Force

# Create a mapped drive with credentials using New-PSDrive for the current session

try {

    New-PSDrive -Name "z" -PSProvider FileSystem -Root $destination -Credential $credentials 

    # Create the update folder if it doesn't exist
    if (-not (Test-Path -Path $destination)) {
        New-Item -ItemType Directory -Path $destination -Force
    }

    # Copying files to the server
    Write-Host "Copying files to $($server)"
    Copy-Item -Path "$($build)\$($buildZip)" -Destination "z:\" -Recurse -Force
    Write-Host "Files copied to $($server)"
} catch {
    Write-Host "Error: $_"
} finally {
    # Remove the mapped drive after copying
    if (Get-PSDrive -Name "z" -ErrorAction SilentlyContinue) {
        Write-Host "Removing mapped drive..."
        Remove-PSDrive -Name "z"
    }
}

write-Host $extractedFolderPath = "$server\$location$(if ($token -eq "usiow2") { "_2" })"

# The script that runs inside the plant.
$plantFunness = {
    param ($server, $token, $location, $buildFile, $buildLoc, $obslst, $obsBuild)

    $localPath = $location -replace '\$', ':'
    $serverFile = "$($localPath)\$buildFile"
    $serverPath = "$($localPath)"
    $appPath = $extractedFolderPath
    $nssmPath = $serverPath + "\nssm.exe"
    $npmPath = "C:\Program Files\nodejs\npm.cmd"  # Path to npm.cmd

    
    Write-Host "In the plant we go!!!!!"

    ######################################################################################
    # Removing the fist and frontend folder to make sure we keep them the same and clean.
    ######################################################################################
    
    # Delete the directories after extraction
    Write-Host "Deleting Dist and Frontend..."

    Set-Location $serverPath
    npm run removeOld # --omit=dev       

    Write-Host "Unzipping the folder..."

    $extractedFolderPath = $serverPath

    # Extract the files to the build path
    try {
        # Expand the archive
        Expand-Archive -Path $serverFile -DestinationPath $extractedFolderPath -Force

        # Delete the zip file after extraction
        Write-Host "Deleting the zip file..."
        Remove-Item -Path $serverFile -Force
    } catch {
        Write-Host "Error: $_"
        exit 1  # Exit with a non-zero code if there's an error
    }

    # Write-Host "-----------------------Dealing with LSTv1 Stuff ------------------------------------"
    # try {
    #     # Expand the archive
    #     Expand-Archive -Path "$($localPath)\$($obsBuild)" -DestinationPath $obslst -Force

    #     # Delete the zip file after extraction
    #     Write-Host "Deleting the zip file..."
    #     Remove-Item -Path "$($localPath)\$($obsBuild)" -Force
    # } catch {
    #     Write-Host "Error: $_"
    #     exit 1  # Exit with a non-zero code if there's an error
    # }

    #  # for iowa 2 need to change the port config on the start up of nextjs server
    #  if($token -eq "usiow2"){
    #     $jsonPkgloc = "$($obslst)\apps\frontend\package.json"
    #     #read the file
    #     $jsonContent = Get-Content -Path $jsonPkgloc | ConvertFrom-Json
    #     #change the second we want to update
    #     $jsonContent.scripts.start = "next start -p 3001"
    #     # convert back to json
    #     $jsonContent | ConvertTo-Json | Set-Content -Path $jsonPkgloc
    # }

    ############################################################################
    Write-Host "Stopping the services to do the updates, pkgs and db changes."

    #Write-Host "Stopping services to update"
    $serviceGateway = "LST-Gateway$(if ($token -eq "usiow2") { "_2" })"
    $serviceAuth = "LST-Auth$(if ($token -eq "usiow2") { "_2" })"
    $serviceSystem = "LST-System$(if ($token -eq "usiow2") { "_2" })"
    $serviceApp = "LST-App$(if ($token -eq "usiow2") { "_2" })"
    $serviceFrontEnd = "LST-frontend$(if ($token -eq "usiow2") { "_2" })"
    $serviceOcme = "LST-Ocme$(if ($token -eq "usiow2") { "_2" })"
    $serviceLstV2 = "LSTV2$(if ($token -eq "usiow2") { "_2" })"

    # if($token -eq "usday1"){
    #     Write-Host "Stopping $($serviceOcme)"
    #     Stop-Service -DisplayName  $serviceOcme -Force
    # }

    # Write-Host "Stopping $($serviceGateway)"
    # Stop-Service -DisplayName $serviceGateway -Force
    # Start-Sleep -Seconds 1

    # Write-Host "Stopping $($serviceAuth)"
    # Stop-Service -DisplayName $serviceAuth -Force
    # Start-Sleep -Seconds 1

    # Write-Host "Stopping $($serviceSystem)"
    # Stop-Service -DisplayName $serviceSystem -Force
    # Start-Sleep -Seconds 1

    # Write-Host "Stopping $($serviceApp)"
    # Stop-Service -DisplayName $serviceApp -Force
    # Start-Sleep -Seconds 1

    # Write-Host "Stopping $($serviceFrontEnd)"
    # Stop-Service -DisplayName $serviceFrontEnd -Force
    # Start-Sleep -Seconds 1 

    Write-Host "Stopping $($serviceLstV2)"
    Stop-Service -DisplayName $serviceLstV2 -Force
    Start-Sleep -Seconds 1 

    #################################################################
    # Service removoal and making sure we have the new version added
    #################################################################

    #################################################################
    # Removing all the old services 
    #################################################################
    Write-Host "Removing services that are no longer used."
    & $nssmPath remove "LogisticsSupportTool" confirm
    & $nssmPath remove $serviceAuth confirm
    & $nssmPath remove $serviceGateway confirm
    & $nssmPath remove $serviceSystem confirm
    & $nssmPath remove $serviceApp confirm
    & $nssmPath remove  $serviceFrontEnd confirm
    & $nssmPath remove $serviceOcme confirm
    # & $nssmPath remove $serviceGateway confirm
    # if($token -eq "usday1"){
    #     & $nssmPath remove $serviceOcme confirm
    # }
    Start-Sleep -Seconds 2

    $service = Get-Service -Name $serviceLstV2 -ErrorAction SilentlyContinue

    if(-not $service){
        ## adding in lstAdm
        Write-Host "Adding $($serviceLstV2)... incase its missing."            
        $commandToRun = "run start"
        $description = "logistics Support Tool"
        & $nssmPath install $serviceLstV2 $npmPath $commandToRun
        Write-Host "Setting the app directory"
        & $nssmPath set $serviceLstV2 AppDirectory $appPath
        Write-Host "Setting the description"
        & $nssmPath set $serviceLstV2 Description $description
        Write-Host "Setting recovery options"
        # Set recovery options
        sc.exe failure $serviceLstV2 reset= 0 actions= restart/5000/restart/5000/restart/5000
    }
    # Doing an install
    Write-Host "Running the install to make sure everything is updated."
    Set-Location $serverPath
    npm run prodinstall # --omit=dev
    Write-Host "Finished doing updates"
    # Start-Sleep -Seconds 1
    # Write-HOst "Running db migrations"
    # npm run db:migrate

    ###########################################################
    # Old system still active until we have everything off it
    ###########################################################

###########################################################
# Frontend env
###########################################################

#     Write-Host "Creating the env file in the front end"
# $envContentTemplatef = @"
# NEXTAUTH_SECRET= "12348fssad5sdg2f2354afvfw34"
# NEXTAUTH_URL_INTERNAL= "http://localhost:3000"
# NEXTAUTH_URL="{url}"
# API_KEY= "E3ECD3619A943B98C6F33E3322362"
# "@
        
#         try {
#             $url = "http://$($token)vms006:3000"
        
#             if ($token -eq "usiow2") {
#                 $url = "http://usiow1vms006:3001"  
#             }
        
#             if ($token -in @("test1", "test2", "test3")) {
#                 $url = "http://usmcd1vms036:3000" 
#             }          
        
#             # Replace {url} with the actual $url
#             $envContentf = $envContentTemplatef -replace "{url}", $url
        
#             # Define the path where the .env file should be created
#             $envFilePathf = $obslst + "\apps\frontend\.env"
#             Write-Host "Final URL: $url"
#             # Write the content to the .env file
#             $envContentf | Out-File -FilePath $envFilePathf -Encoding UTF8 -Force
        
#             # Optional: Verify the file was created
#             if (Test-Path $envFilePathf) {
#                 Write-Host "`.env` file created successfully on $env:COMPUTERNAME at $envFilePathf"
#             } else {
#                 Write-Host "Failed to create `.env` file on $env:COMPUTERNAME"
#             }
        
#         } catch {
#             Write-Host "Error: Failed to create `.env` file on $server - $_"
#         }

###########################################################
# DB env
###########################################################

# Write-Host "Creating the env file in the front end"
# $envContentTemplateb = @"
# DATABASE_URL="file:E:\LST\db\{dbLink}.db"
# "@
        
#         try {

#             $dbLink = "lstBackendDB"
        
#             if ($token -eq "usiow2") {
#                 $dbLink = "lstBackendDB_2"  
#             }
        
#             if ($token -in @("test1", "test2", "test3")) {
#                 $dbLink = "lstBackendDB" 
#             }          
        
#             # Replace {url} with the actual $url
#             $envContentb = $envContentTemplateb -replace "{dbLink}", $dbLink
       
#             # Define the path where the .env file should be created
#             $envFilePathb = $obslst + "\packages\database\.env"
           
#             # Write the content to the .env file
#             $envContentb | Out-File -FilePath $envFilePathb -Encoding UTF8 -Force
        
#             # Optional: Verify the file was created
#             if (Test-Path $envFilePathb) {
#                 Write-Host "`.env` file created successfully on $env:COMPUTERNAME at $envFilePathb"
#             } else {
#                 Write-Host "Failed to create `.env` file on $env:COMPUTERNAME"
#             }
        
#         } catch {
#             Write-Host "Error: Failed to create `.env` file on $server - $_"
#         }    

###########################################################
# backend env
###########################################################

# Write-Host "Creating the env file in the front end"
# $envContentTemplated = @"
# # Server env
# NODE_ENV = production 
# # server apiKey
# API_KEY = E3ECD3619A943B98C6F33E3322362
# # Prisma DB link
# DATABASE_URL="file:E:\LST\db\{dbLink}.db"
# # if you still want the db in the same folder as the server install you need to do like the example below else use the relevent link
# DATEBASE_LOC="E:\LST\db\{dbLink}.db"
# DATABASE_BACKUP_LOC="E:\LST\backups"
# # Server port
# GATEWAY_PORT={gatewayport}
# AUTH_PORT=4100
# SYSTEM_APP_PORT={systemport}
# OCME_PORT={ocme}

# # This should me removed once we have the entire app broke out to its own apps
# OLD_APP_PORT={appPort}

# # Logging
# LOG_LEVEL = info
# LOG_LOC ="E:\\LST\\logs"

# # authentication 
# SALTING = 12
# SECRET = E3ECD3619A943B98C6F33E3322362
# JWT_SECRET = 12348fssad5sdg2f2354afvfw34
# JWT_EXPIRES_TIME = 1h

# # cookie time is in min please take this into consideration when creating all the times
# COOKIE_EXPIRES_TIME = 60

# # password token reset in mintues 
# RESET_TOKEN = 330
# "@
        
# try {

#     $dbLink = "lstBackendDB"
#     $gatewayport = "4400"
#     $systemport = "4200"
#     $ocmeport = "4300"
#     $appport = "4400"

#     if ($token -eq "usiow2") {
#         $dbLink = "lstBackendDB_2"  
#         $gatewayport = "4401"
#         $systemport = "4201"
#         $ocmeport = "4301"
#         $appport = "4401"
#     }

#     if ($token -in @("test1", "test2", "test3")) {
#         $dbLink = "lstBackendDB" 
#     }          

#     # 
#     $port1 = $envContentTemplated -replace "{gatewayport}", $gatewayport
#     $port2 = $port1 -replace "{systemport}", $systemport
#     $port3 = $port2 -replace "{ocme}", $ocmeport
#     $port4 = $port3 -replace "{appPort}", $appport
#     $envContentd = $port4 -replace "{dbLink}", $dbLink


#     # Define the path where the .env file should be created
#     $envFilePathd = $obslst + "\.env"
   
#     # Write the content to the .env file
#     $envContentd | Out-File -FilePath $envFilePathd -Encoding UTF8 -Force
        
#             # Optional: Verify the file was created
#             if (Test-Path $envFilePathd) {
#                 Write-Host "`.env` file created successfully on $env:COMPUTERNAME at $envFilePathd"
#             } else {
#                 Write-Host "Failed to create `.env` file on $env:COMPUTERNAME"
#             }
        
#         } catch {
#             Write-Host "Error: Failed to create `.env` file on $server - $_"
#         }  


    # Write-Host "Running install on obs server."
    # Set-Location $obslst
    # npm run newinstall # --omit=dev
    # Write-Host "Update the frontend"
    # npm run install:front
    # npm run install:ui
    # npm run install:db

    # Write-Host "Running db updates"
    # npm run db:migrate
    # Start-Sleep -Seconds 1
    # npm run db:gen
    # Start-Sleep -Seconds 1
    # Write-Host "incase a new default setting was added we want to add it in."
    # npm run db:init

    ###########################################################
    # Starting the services back up.
    ###########################################################
    # Write-Host "Starting the services"
    # Write-Host "Starting $($serviceSystem)"
    # Start-Service -DisplayName $serviceSystem 
    # Start-Sleep -Seconds 1
    # Write-Host "Starting $($serviceGateway)"
    # Start-Service -DisplayName $serviceGateway
    # Start-Sleep -Seconds 1
    # Write-Host "Starting $($serviceAuth)"
    # Start-Service -DisplayName $serviceAuth
    # Start-Sleep -Seconds 1
    # Write-Host "Starting $($serviceApp)"
    # Start-Service -DisplayName $serviceApp 
    # Start-Sleep -Seconds 1
    # Write-Host "Starting $($serviceFrontEnd)"
    # Start-Service -DisplayName $serviceFrontEnd 
    # Start-Sleep -Seconds 1
    Write-Host "Starting $( $serviceLstV2)"
    Start-Service -DisplayName  $serviceLstV2
    Start-Sleep -Seconds 1
    Write-Host "$($server) finished updating"
    # if($token -eq "usday1"){
    #     Write-Host "Starting $($serviceOcme)"
    #     Start-Service -DisplayName  $serviceOcme 
    # }

}
Invoke-Command -ComputerName $server -ScriptBlock $plantFunness -ArgumentList $server, $token, $location, $buildZip, $buildLoc, $obslst, $obsBuild -Credential $credentials