. "$PSScriptRoot/../../lib/PowerManagement.ps1";
. "$PSScriptRoot/../../../lib/Software.ps1";

& {
    <#
        .SYNOPSIS
        Gets the path to the Nextcloud configuration file.
    #>
    function Get-ConfigFile {
        return "$env:APPDATA/Nextcloud/nextcloud.cfg";
    }

    <#
        .SYNOPSIS
        Adds a new nextcloud sync to the current user.
    #>
    function Add-NextcloudSync {
        param(
            [string] $RemotePath,
            [string] $LocalPath,
            [switch] $VirtualFiles
        )

        Write-Host "Adding a Nextcloud sync";
        Write-Host "$RemotePath <=> $LocalPath";
        $configName = "Folders";
        $virtualName = "WithPlaceholders";
        $LocalPath = $LocalPath.Replace("\", "/");
        $RemotePath = $RemotePath.Replace("\", "/");
        $oldContent = Get-Content (Get-ConfigFile);
        $additionalSettings = @();
        $pattern = "^\d+\\$configName(?:$virtualName)?\\(\d+)";

        $folderID = (
            $oldContent | `
                Where-Object { $_ -match "$pattern" } | `
                ForEach-Object { $_ -replace "$pattern.*$", "`$1" } | `
                Sort-Object -Unique | `
                Measure-Object -Maximum).Maximum + 1;

        if ($VirtualFiles.IsPresent) {
            $configName += $virtualName;
            $additionalSettings = @("0\$configName\$folderID\virtualFilesMode=wincfapi");
        }

        $newSettings = (
            @(
                "0\$configName\$folderID\localPath=$LocalPath",
                "0\$configName\$folderID\targetPath=$RemotePath"
            ) + $additionalSettings
        ) -join "`n";

        & {
            $accountSectionEntered = $false;
            $accountSectionLeft = $false;

            for ($i = 0; $i -lt $oldContent.Count; $i++) {
                $line = $oldContent[$i];

                if ($line -eq "[Accounts]") {
                    $accountSectionEntered = $true;
                }

                if ($line -eq "" -and $accountSectionEntered) {
                    $accountSectionLeft = $true;
                    $newSettings;
                }

                $line;

                if (
                    (-not $accountSectionLeft) -and
                    ($i -eq ($oldContent.Count - 1))) {
                    $newSettings;
                }
            }
        } | Set-Content (Get-ConfigFile);
    }


    Start-SoftwareInstaller @args `
        -Installer {
            Install-ChocoPackage nextcloud-client -ArgumentList "-y", "--params='/KeepUpdateCheck'";
        } `
        -UserConfigurator {
            param($Arguments)
            $user = $Arguments.Name;

            & {
                $syncs = Get-UserConfig -UserName $user "programs.nextcloud.folderSyncs";
                $configExists = { (Test-Path (Get-ConfigFile) ) };

                if ($syncs.Count -gt 0) {
                    if (-not (& $configExists)) {
                        while (-not (& $configExists)) {
                            Read-Host "Please log in to the Nextcloud app and hit enter to continue";

                            if (-not (& $configExists)) {
                                Write-Error -ErrorAction Continue "The login seems to have failed. Please try again.";
                            }
                        }
                    }

                    Write-Host "Stopping Nextcloud process";
                    $nextcloudProcess = Get-Process nextcloud;
                    $nextcloudPath = [string]$nextcloudProcess[0].Path;
                    $nextcloudProcess | Stop-Process -Force;

                    foreach ($sync in $syncs) {
                        Add-NextcloudSync -LocalPath $sync.localPath -RemotePath $sync.remotePath -VirtualFiles:$sync.virtualFiles;
                    }

                    Write-Host "Restarting Nextcloud";
                    Start-Process $nextcloudPath;
                }
            };
        };
} @args;