# Load configuration from JSON file
$config = Get-Content -Raw -Path "$PSScriptRoot\config.json" | ConvertFrom-Json

# Set paths from configuration
$sourceFile = Join-Path $config.deploymentDir $config.ear.deployedFile
$destinationPath = $config.ear.unpackDir

# Remove destination directory if it exists
if (Test-Path -Path $destinationPath) {
    Remove-Item -Path $destinationPath -Recurse -Force
    Write-Host "Removed existing directory: $destinationPath"
}

# Create destination directory
if (-not (Test-Path -Path $destinationPath)) {
    New-Item -ItemType Directory -Path $destinationPath -Force
}

# Rename .ear to .zip temporarily to use Expand-Archive
$tempZipPath = $sourceFile -replace '\.ear$', '.zip'
Copy-Item -Path $sourceFile -Destination $tempZipPath

# Extract the EAR contents
Expand-Archive -Path $tempZipPath -DestinationPath $destinationPath -Force

# Clean up temporary zip file
Remove-Item -Path $tempZipPath

Write-Host "EAR file extracted to $destinationPath"

# Function to unpack archive files (war/ejb)
function Expand-JavaArchive {
    param (
        [string]$archivePath,
        [string]$destinationPath
    )
    
    $tempZipPath = $archivePath -replace '\.(war|jar)$', '.zip'
    Copy-Item -Path $archivePath -Destination $tempZipPath
    
    # Create extraction directory
    if (-not (Test-Path -Path $destinationPath)) {
        New-Item -ItemType Directory -Path $destinationPath -Force
    }
    
    # Extract contents
    Expand-Archive -Path $tempZipPath -DestinationPath $destinationPath -Force
    Remove-Item -Path $tempZipPath
    Write-Host "Extracted $archivePath to $destinationPath"
}

# Find and extract WAR and EJB files
Get-ChildItem -Path $destinationPath -Recurse -Include "*.war", "*-ejbx.jar" | ForEach-Object {
    $extractPath = Join-Path (Split-Path -Parent $_.FullName) ($_.BaseName + "_unpacked")
    Expand-JavaArchive -archivePath $_.FullName -destinationPath $extractPath
}