#!/usr/bin/perl -w
#
# check-vhosts:
# Check each server has exactly the set of vhosts deployed as
# documented in vhosts.pl. TODO: Also check against DNS
#
# Copyright (c) 2006 UK Citizens Online Democracy. All rights reserved.
# Email: francis@mysociety.org; WWW: http://www.mysociety.org/
#

my $rcsid = ''; $rcsid .= '$Id: check-vhosts,v 1.4 2012-09-26 15:38:55 matthew Exp $';

package main;

use strict;
require 5.8.0;

use FindBin;
use lib "$FindBin::Bin/../perllib";
my $mysociety_bin = $FindBin::Bin;
my $servers_dir = "$FindBin::Bin/../../servers";
my $mysociety_dir = "$FindBin::Bin/../../mysociety";

use mySociety::ArrayUtils;
use Data::Dumper;
use File::Slurp;

our $verbose = $ENV{VERBOSE} ? 1 : 0;

#####################################################################
# Main code

# Read in configuration file
our ($vhosts, $sites);
require "$servers_dir/vhosts.pl";

# Read list of servers for each vhost
my $servers_to_vhosts;
foreach my $vhost ( keys (%$vhosts) ) {
    my $servers = $vhosts->{$vhost}->{servers}; 
    foreach my $server ( @$servers ) {
        push @{$servers_to_vhosts->{$server}}, $vhost;
    }
}

# For each server, check vhost list
foreach my $server ( keys (%$servers_to_vhosts) ) {
    print "Server: $server\n" if $verbose;

    # Get list of expected
    my $expected_vhosts = $servers_to_vhosts->{$server};
    push @{$expected_vhosts}, "default.ukcod.org.uk"; # server should have own vhost
    print "Expected: " . Dumper($expected_vhosts) if $verbose;

    # Get list in /data/vhost on server
    my $deployed_vhosts;
    my $vhost_list = "$servers_dir/../state/$server/vhost-list";
    open FH, $vhost_list or die "$vhost_list not found";
    while (<FH>) {
        $_ =~ s/\s+$//;
        $_ =~ s/^\s+//;
        if (m/^(debian.mysociety.org|index.html|wdg-html-validator.html|index.lighttpd.html)$/) {
            # just ignore these - files from Debian packaging or our config system
            next;
        } 
        push @{$deployed_vhosts}, $_;
    }
    print "Deployed: " . Dumper($deployed_vhosts) if $verbose;

    my $symmetric_diff = mySociety::ArrayUtils::symmetric_diff($deployed_vhosts, $expected_vhosts);
    if (scalar @$symmetric_diff > 0) {
        print "For server '$server' the following vhosts mismatch between vhosts.pl and folders in /data/vhost:\n";
        foreach my $notright (@$symmetric_diff) {
            print "\t$notright\n";
        }
    }
}

