#!/usr/bin/env bash
set -euo pipefail

APP_ID="c55ca600-29f4-42b5-8c9a-a2d53153f8a2"

if ! command -v pwsh >/dev/null 2>&1; then
    echo "Fel: PowerShell 7 (pwsh) är inte installerat."
    exit 1
fi

export ADD_IT_APP_ID="$APP_ID"

PS_SCRIPT="$(mktemp /tmp/activate-add-it-ews.XXXXXX.ps1)"
trap 'rm -f "$PS_SCRIPT"' EXIT

cat > "$PS_SCRIPT" <<'POWERSHELL'
$ErrorActionPreference = "Stop"
$appId = $env:ADD_IT_APP_ID

function Get-EwsAppIds {
    param($Configuration)
    return @(
        $Configuration.EwsAllowedAppIDs |
        ForEach-Object { "$_" -split "," } |
        ForEach-Object { $_.Trim() } |
        Where-Object { $_ } |
        Sort-Object -Unique
    )
}

function Show-EwsStatus {
    param($Configuration, [string]$TargetAppId, [string]$Heading)

    $appIds = @(Get-EwsAppIds -Configuration $Configuration)
    $ewsStatus = if ($null -eq $Configuration.EwsEnabled) { "Null" } else { "$($Configuration.EwsEnabled)" }

    Write-Host ""
    Write-Host "==================================================" -ForegroundColor DarkGray
    Write-Host $Heading -ForegroundColor Cyan
    Write-Host "==================================================" -ForegroundColor DarkGray

    switch ($ewsStatus.ToLowerInvariant()) {
        "true" {
            Write-Host "EWS-status: AKTIVERAD (True)" -ForegroundColor Green
            if ($appIds.Count -gt 0) {
                Write-Host "Endast appar i EWSAllowedAppIDs är tillåtna."
            } else {
                Write-Host "Varning: EWS är aktiverat men applistan är tom." -ForegroundColor Yellow
            }
        }
        "false" {
            Write-Host "EWS-status: AVSTÄNGD (False)" -ForegroundColor Red
            Write-Host "Alla EWS-anrop är blockerade."
        }
        default {
            Write-Host "EWS-status: INTE UTTRYCKLIGEN SATT (Null)" -ForegroundColor Yellow
            Write-Host "Microsoft kan ändra värdet till False under avvecklingsperioden." -ForegroundColor Yellow
        }
    }

    Write-Host ""
    Write-Host "EWSAllowedAppIDs:" -ForegroundColor Cyan
    if ($appIds.Count -eq 0) {
        Write-Host "  Applistan är tom." -ForegroundColor Yellow
    } else {
        foreach ($id in $appIds) {
            if ($id -eq $TargetAppId) {
                Write-Host "  [OK] Add it: $id" -ForegroundColor Green
            } else {
                Write-Host "  [BEFINTLIG APP] $id"
            }
        }
    }

    if ($appIds -contains $TargetAppId) {
        Write-Host "Add it finns i applistan: JA" -ForegroundColor Green
    } else {
        Write-Host "Add it finns i applistan: NEJ" -ForegroundColor Red
    }
    Write-Host "==================================================" -ForegroundColor DarkGray
}

if (-not (Get-Module -ListAvailable -Name ExchangeOnlineManagement)) {
    Write-Host "Installerar ExchangeOnlineManagement..." -ForegroundColor Yellow
    Install-Module -Name ExchangeOnlineManagement -Scope CurrentUser -Force -AllowClobber
}

Import-Module ExchangeOnlineManagement

Write-Host "Ansluter till Exchange Online..." -ForegroundColor Cyan
Write-Host "Följ Microsofts inloggningsinstruktioner och återgå sedan hit." -ForegroundColor Yellow
Connect-ExchangeOnline -Device -ShowBanner:$false

try {
    $before = Get-OrganizationConfig -RetrieveEwsOperationAccessPolicy
    Show-EwsStatus -Configuration $before -TargetAppId $appId -Heading "STATUS FÖRE ÄNDRING"

    $currentAppIds = @(Get-EwsAppIds -Configuration $before)
    $updatedAppIds = @($currentAppIds + $appId | Where-Object { $_ } | Sort-Object -Unique)

    Write-Host ""
    Write-Host "Föreslagen ny lista:" -ForegroundColor Cyan
    $updatedAppIds | ForEach-Object { Write-Host "  $_" }

    Write-Host ""
    $confirmation = Read-Host "Skriv JA för att uppdatera applistan och aktivera EWS"
    if ($confirmation -cne "JA") {
        Write-Host "Ingen ändring genomfördes." -ForegroundColor Yellow
        return
    }

    Set-OrganizationConfig -EwsAllowedAppIDs ($updatedAppIds -join ",")
    Set-OrganizationConfig -EwsEnabled $true

    $after = Get-OrganizationConfig -RetrieveEwsOperationAccessPolicy
    Show-EwsStatus -Configuration $after -TargetAppId $appId -Heading "STATUS EFTER ÄNDRING"

    $verifiedAppIds = @(Get-EwsAppIds -Configuration $after)
    if (($after.EwsEnabled -eq $true) -and ($verifiedAppIds -contains $appId)) {
        Write-Host ""
        Write-Host "SLUTRESULTAT: GODKÄNT" -ForegroundColor Green
        Write-Host "EWS är aktiverat och Add it finns i applistan." -ForegroundColor Green
    } else {
        Write-Host ""
        Write-Host "SLUTRESULTAT: KUNDE INTE VERIFIERAS" -ForegroundColor Red
        exit 1
    }

    Write-Host ""
    Write-Host "Observera: liständringen kan ta upp till 24 timmar att slå igenom." -ForegroundColor Yellow
}
finally {
    Disconnect-ExchangeOnline -Confirm:$false -ErrorAction SilentlyContinue
}
POWERSHELL

pwsh -NoLogo -NoProfile -File "$PS_SCRIPT"
