using System;
using System.Collections.Generic;
using System.Management.Automation;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PSProxmox.Client;
using PSProxmox.Models;
using PSProxmox.Session;
using PSProxmox.Utilities;
namespace PSProxmox.Cmdlets
{
///
/// Gets cluster backups from Proxmox VE.
/// The Get-ProxmoxClusterBackup cmdlet retrieves cluster backups from Proxmox VE.
///
/// Get all cluster backups
/// $backups = Get-ProxmoxClusterBackup -Connection $connection
///
///
/// Get a specific cluster backup by ID
/// $backup = Get-ProxmoxClusterBackup -Connection $connection -BackupID "vzdump-cluster-2023_04_28-12_00_00.vma.lzo"
///
///
[Cmdlet(VerbsCommon.Get, "ProxmoxClusterBackup")]
[OutputType(typeof(ProxmoxClusterBackup), typeof(string))]
public class GetProxmoxClusterBackupCmdlet : PSCmdlet
{
///
/// The connection to the Proxmox VE server.
///
[Parameter(Mandatory = true, Position = 0)]
public ProxmoxConnection Connection { get; set; }
///
/// The ID of the backup to retrieve.
///
[Parameter(Mandatory = false)]
public string BackupID { get; set; }
///
/// Whether to return the raw JSON response.
///
[Parameter(Mandatory = false)]
public SwitchParameter RawJson { get; set; }
///
/// Processes the cmdlet.
///
protected override void ProcessRecord()
{
try
{
var client = new ProxmoxApiClient(Connection, this);
string response;
response = client.Get("cluster/backup");
var backupsData = JsonUtility.DeserializeResponse(response);
var backups = new List();
foreach (var backupObj in backupsData)
{
var backup = backupObj.ToObject();
if (string.IsNullOrEmpty(BackupID) || backup.BackupID == BackupID)
{
backups.Add(backup);
}
}
if (RawJson.IsPresent)
{
WriteObject(response);
}
else if (string.IsNullOrEmpty(BackupID))
{
WriteObject(backups, true);
}
else if (backups.Count > 0)
{
WriteObject(backups[0]);
}
else
{
WriteError(new ErrorRecord(
new Exception($"Backup with ID {BackupID} not found"),
"BackupNotFound",
ErrorCategory.ObjectNotFound,
BackupID));
}
}
catch (Exception ex)
{
WriteError(new ErrorRecord(ex, "GetProxmoxClusterBackupError", ErrorCategory.OperationStopped, Connection));
}
}
}
}