using Sharp.Augeas;
namespace CodeLiturgy.Views.Augeas
{
///
/// Manager class for Augeas.
///
public class AugeasManager
{
private readonly Sharp.Augeas.Augeas _augeas;
private AugSettings _augSettings;
///
/// Cached List with the current apache configurations.
///
public List CurrentApacheConfigurations => _currentApacheConfigurations;
private List _currentApacheConfigurations;
private const string ApachePath = "/etc/apache2/sites-available";
///
/// Augeas Manager constructor.
///
public AugeasManager()
{
_augSettings = AugeasExtensions.GetSettings();
_augeas = new Sharp.Augeas.Augeas(_augSettings);
RefreshApacheConfigurations();
}
///
/// Write Changes to the disk
///
/// Returns true if the save was successful.
public bool Save()
{
return _augeas.Save();
}
///
/// Gets a preview of the configuration.
///
///
///
public string GetPreview(string site)
{
if (!_currentApacheConfigurations.Contains(site))
{
return string.Empty;
}
var siteFullPath = $"{ApachePath}/{site}";
_augeas.LoadFile(siteFullPath);
var preview = _augeas.GetPreview($"/files{siteFullPath}");
return preview;
}
///
/// Gets available Apache configurations.
///
///
///
///
public List GetApacheAvailableConfigurations(int skip, int take)
{
var result = _currentApacheConfigurations
.Skip(skip)
.Take(take)
.ToList();
return _currentApacheConfigurations;
}
///
/// Gets virtual host tree of a site.
///
/// Name of the site.
///
public SuperNode GetVirtualHostTree(string site)
{
if (!_currentApacheConfigurations.Contains(site))
{
return null;
}
var siteFullPath = $"{ApachePath}/{site}";
_augeas.LoadFile(siteFullPath);
var tree = _augeas.GetTree("VirtualHost",$"/files{siteFullPath}/VirtualHost/*");
return tree;
}
private void RefreshApacheConfigurations()
{
var apacheDir = _augSettings.root + ApachePath;
DirectoryInfo d = new DirectoryInfo(apacheDir);
FileInfo[] files = d.GetFiles("*.conf");
var result = files
.Select(x => x.Name)
.ToList();
_currentApacheConfigurations = result;
}
///
/// Gets a directive.
///
///
///
///
public Directive GetDirective(string siteName, string directiveName)
{
var tree = GetVirtualHostTree(siteName);
var directive = tree.GetDirective(directiveName);
return directive;
}
}
}