using System;
using System.Management.Automation;
using System.Security;
using PSProxmox.Models;
using PSProxmox.Session;
namespace PSProxmox.Cmdlets
{
///
/// Connects to a Proxmox VE server.
/// The Connect-ProxmoxServer cmdlet establishes a connection to a Proxmox VE server and returns a connection object that can be used with other cmdlets.
///
/// Connect to a Proxmox VE server using a credential object
/// $credential = Get-Credential
/// $connection = Connect-ProxmoxServer -Server "proxmox.example.com" -Credential $credential
///
///
/// Connect to a Proxmox VE server with explicit username and password
/// $securePassword = ConvertTo-SecureString "password" -AsPlainText -Force
/// $connection = Connect-ProxmoxServer -Server "proxmox.example.com" -Username "root" -Password $securePassword -Realm "pam"
///
///
[Cmdlet(VerbsCommunications.Connect, "ProxmoxServer")]
[OutputType(typeof(ProxmoxConnectionInfo))]
public class ConnectProxmoxServerCmdlet : PSCmdlet
{
///
/// The server hostname or IP address.
///
[Parameter(Mandatory = true, Position = 0)]
public string Server { get; set; }
///
/// The port number.
///
[Parameter(Mandatory = false)]
public int Port { get; set; } = 8006;
///
/// Whether to use HTTPS.
///
[Parameter(Mandatory = false)]
public SwitchParameter UseSSL { get; set; } = true;
///
/// Whether to skip SSL certificate validation.
///
[Parameter(Mandatory = false)]
public SwitchParameter SkipCertificateValidation { get; set; }
///
/// The credential object containing username and password.
///
[Parameter(Mandatory = false, ParameterSetName = "Credential")]
public PSCredential Credential { get; set; }
///
/// The username for authentication.
///
[Parameter(Mandatory = true, ParameterSetName = "UsernamePassword")]
public string Username { get; set; }
///
/// The password for authentication.
///
[Parameter(Mandatory = true, ParameterSetName = "UsernamePassword")]
public SecureString Password { get; set; }
///
/// The realm for authentication.
///
[Parameter(Mandatory = false)]
public string Realm { get; set; } = "pam";
///
/// Processes the cmdlet.
///
protected override void ProcessRecord()
{
try
{
string username;
SecureString password;
if (ParameterSetName == "Credential")
{
if (Credential == null)
{
throw new PSArgumentNullException(nameof(Credential));
}
username = Credential.UserName;
password = Credential.Password;
}
else
{
username = Username;
password = Password;
}
var connection = ProxmoxSession.Login(
Server,
Port,
UseSSL.IsPresent,
SkipCertificateValidation.IsPresent,
username,
password,
Realm,
this);
WriteObject(ProxmoxConnectionInfo.FromConnection(connection));
SessionState.PSVariable.Set(new PSVariable("ProxmoxConnection", connection, ScopedItemOptions.Private));
}
catch (Exception ex)
{
WriteError(new ErrorRecord(ex, "ConnectProxmoxServerError", ErrorCategory.ConnectionError, Server));
}
}
}
}