#!/usr/bin/perl -w

# vim: ft=perl:

use strict;
use esmith::DomainsDB;
use esmith::event;

my $d = esmith::DomainsDB->open or die "Couldn't open the domain database\n";

my @domains = ();

# Build a list of domains for which we disable ACME challenge proxypass
# but only during execution of letsencrypt
# This is usefull for situations where you have a https website directly reachable
# from your internal network, but going through a proxypass from the outside. In this case
# both the backend and the frontend needs to have a valid certificate for this name

foreach my $dom ($d->domains, $d->get_all_by_prop(type => 'vhost')){
    if (($dom->prop('ProxyPassACMEChallengesDisableOnRenew') || 'no') =~ m/^yes|enabled|1|on$/){
        push @domains, $dom;
    }
}

# Now, temporarily disable ACME chellenge proxypass
if (@domains > 0){
    foreach my $dom (@domains){
      $dom->set_prop('ProxyPassACMEChallenges', 'disabled');
    }
    event_signal("letsencrypt-update");
}

# Execute the real dehydrated script, passing any arg
system("/usr/bin/dehydrated", @ARGV);

# Enable proxypass again
if (@domains > 0){
    foreach my $dom (@domains){
        $dom->set_prop('ProxyPassACMEChallenges', 'enabled');
    }
    event_signal("letsencrypt-update");
}
