package httpd;

use warnings;
use strict;
use autodie;

=head1 httpd

Start with:

  perl -Ilib/PXElator -Mhttpd -e httpd::start

=cut

use Data::Dump qw/dump/;
use Carp qw/confess/;
use File::Slurp;
#use JSON;
use IO::Socket::INET;
use Regexp::Common qw/net/;
use POSIX qw(strftime);

our $title;

sub html_start {
qq{
<html>
<head>
<title>$title</title>
</head>
<body>
}}

sub html_end {
qq{
</body>
</html>
}}

our $port = 7777;

use server;
our $debug = server::debug;
our $url = "http://$server::ip:$port";

use html;
our $static_pids;
use progress_bar;
use config;
use client;
use log;
use x11;
use amt;
use daemons;

use kvm;
use browser;
use network;
use ip;
use wireshark;
use syslogd;
use nmap;
use ping;
use wol;

use store;


sub menu {
	my $store_url = $url;
	$store_url =~ s{:\d+.+}{:28017};
qq{
<div style="font-size: 80%; color: #888">
<a target=pids href=/ >home</a>
|
<a target=server href=/server >server</a>
<a target=server href=/brctl >brctl</a>
<a target=server href=/ip >ip</a>
|
<a target=store href=$store_url >MongoDB</a>
<a target=store href=/store/latest >latest</a>
|
<a target=client href=/nmap >nmap</a>
<a target=client href=/client >client</a>
</div>

}}


sub static {
	my ($client,$path) = @_;

	my $full = "$server::base_dir/tftp/$path";

	return if ! -f $full;

	return if $full =~ m{\.ico$};

	if ( my $pid = fork ) {
		# parent
		close($client);
		$static_pids->{$pid} = $path;
		return 1;
	}

	my $type = 'application/octet-stream';
	$type = 'text/html' if $path =~ m{\.htm};
	$type = 'application/javascript' if $path =~ m{\.js};
	$type = 'text/plain' if $path =~ m{\.txt};

	my $size = -s $full || return;

	print $client "HTTP/1.0 200 OK\r\nContent-Type: $type\r\nContent-Length: $size\r\nConnection: close\r\n\r\n";

	open(my $fh, $full);

	my $block = 1400; # try not to fragment packages (pxelinux seems to have problems with it)
	my $buff;
	my $pos = 0;

	store::audit( 'static', { pid => $$, path => $path, type => $type, size => $size, block => $block, peerhost => $client->peerhost });

	progress_bar::start;

	while( my $len = read $fh, $buff, $block ) {
		print $client $buff;
		$client->flush;
		$pos += $len;
		progress_bar::tick( $path, $pos, $size );
	}
	close($fh);
	close($client);

	print STDERR "\n";

	exit(0);
}

sub ok {
	qq|HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n| . html_start() . menu()
}

sub redirect {
	my $to = shift;
	$to ||= $url;
	qq|HTTP/1.1 302 Found\r\nContent-type: text/html\r\nLocation: $to\r\n\r\n|
}

sub toggle {
	my $v = shift;
	return $v ? 0 : 1;
}

sub get_request {
	my ( $client, $path, $param ) = @_;

	server->refresh;

	store::audit( 'request', { path => $path, param => $param, peerhost => $client->peerhost } );

	$title = $path;

	if ( my $found = static( $client,$path ) ) {
		warn "static $found" if $debug;
	} elsif ( $path eq '/' ) {

		my @rows;

		my $debug_proc = '';

warn "XXX pids = ", dump( $daemons::pids );

		foreach my $name ( sort keys %$daemons::pids ) {
			my $pid = $daemons::pids->{$name}; # || next;

			my $html;

			my $proc = "/proc/$pid/status";

			if ( -e $proc ) {
				$html .= qq|<a href=/start_stop/$name>$pid</a>|;
				if ( $debug ) {
					$html .= qq| <a name=$pid href=#proc-$pid>?</a>| if $name->can('start');

					$debug_proc
						.= qq|<a name=proc-$pid href=#$pid>$proc</a><pre style="font-size: 10%">|
						.  read_file($proc)
						.  qq|</pre>|
						;
				}

				my $class = $name;
				$class =~ s{\.\d+$}{};

				if ( $class->can('fork_if_active') ) {
					$html .= qq| <a href=/start_stop/$name/$_>$_</a>| foreach $class->fork_if_active;
				}

				if ( $class->can('actions') ) {
					$html .= qq| <a href=/action/$name/$_>$_</a>| foreach $class->actions;
				}
			} else {
				if ( $pid =~ m{^\d+$} ) {
					$html .= qq|$pid exited |
				} else {
					$html .= qq|$pid |;
				}
				$html .= qq|<a href=/start_stop/$name>restart</a>| if $pid || $name->can('start');
				if ( $name->can('fork_actions') ) {
					$html .= qq| <a href=/start_stop/$name/$_>$_</a>| foreach $name->fork_actions;
				}
			}

			die "no html generated" unless $html;

			push @rows, ( $name => $html );
		}

		my $below_table = '';

		warn 'static_pids: ', dump( $static_pids ) if $debug;
		foreach my $pid ( keys %$static_pids ) {
			my $path = $static_pids->{$pid};
			if ( -d "/proc/$pid" ) {
				push @rows, ( $path => qq|<a href=/kill/static/$pid>$pid</a>| );
			} elsif ( $param->{clean_completed_downloads} ) {
				delete $static_pids->{$pid}
			} else {
				push @rows, ( $path => "$pid competed" );
				$below_table = qq|<a href="/?clean_completed_downloads=1">clean completed downloads</a>|;
			}
		}

		my $kvm = kvm::next_nr;
		$kvm = qq|<div><a href=/start_stop/kvm?nr=$kvm>create new kvm $kvm</a></div>|;

		print $client ok
			, html::table( 2, @rows )
			, $below_table
			, $kvm
			, html::tabs( log::mac_changes )
			, $debug_proc
			;

	} elsif ( $path =~ m{^/server} ) {
		foreach my $name ( keys %$param ) {
			eval '$server::' . $name . '= $param->{$name}';
		}
		my @table = (
			  'debug' => qq|<a href=/our/debug/| . toggle($debug) . qq|>$debug</a>|,
			, 'new_clients' => qq|<input type=text name=new_clients size=3 value="$server::new_clients">|
		);

		foreach my $editable ( 'ip', 'bcast', 'netmask', 'ip_from', 'ip_to', 'domain' ) {
			my $v = eval '$server::' . $editable;
			push @table, ( $editable, qq|<input type=text name=$editable value="$v">| );
		}

		foreach my $readonly ( 'base_dir', 'conf' ) {
			my $v = eval '$server::' . $readonly;
			push @table, ( $readonly, html::tt $v );
		}
			
		print $client ok
			, qq|<form method=get>|
			, html::table( 2, @table )
			, qq|
				<input type=submit name=action value=change>
				</form>
			|
			;

	} elsif ( $path =~ m{^/store/latest} ) {
		print $client ok
			, qq|
<style type=text/css>
	.z {
		background: #eee;
	}
	td > pre {
		margin: 0;
		max-height: 3em;
		overflow: hidden;
	}
	td:hover > pre {
		max-height: 100%;
		overflow: show;
	}
</style>
			|
			, qq|<table>|
		;
		my ( $s1,$s2 ) = ( ' class=z', '' );
		my @cols;

		store::query( sub {
			my $o = shift;
			my $p = delete( $o->{package} );
			delete( $o->{_id} );

			if ( ! @cols ) {
				#@cols = keys %$p;
				@cols = qw( time name );
				print $client qq|<tr><th>|
					, join(qq|</th><th>|, @cols)
					, qq|</th><th></th></tr>|
				;
			}

			# XXX sigh, dump dies if we don't do this
#			delete $o->{$_} foreach ( grep { ! defined $o->{$_} } keys %$o );

			print $client qq|<tr$s1>|
				, strftime( qq|<td title="%Y-%m-%d">%H:%M:%S</td>|, localtime($p->{time}) )
				, map { qq|<td>$_<td>| } ( $p->{name} , html::pre_dump($o) )
				, qq|</tr>\n|
			;
			( $s1, $s2 ) = ( $s2, $s1 );
		});
		print $client qq|</table>|;

	} elsif ( $path =~ m!^/client(?:/$RE{net}{IPv4}{-keep})?! ) {
		my $ip = $1;
		$title = $ip if $ip;

		if ( $param->{action} eq 'remove' ) {
			client::remove( $param->{change_ip} );
			print $client redirect("$url/client");
			return;
		} elsif ( $param->{action} eq 'change' ) {
			if ( my $new_ip = client::change_ip( $ip, $param->{change_ip} ) ) {
				print $client redirect("$url/client#$new_ip");
				return;
			}
		}

 		if ( ! $ip ) {
			my $peer_ip = $client->peerhost;

			my $netmask  = ip::to_int $server::netmask;
			my $network  = ip::to_int($server::ip) & $netmask;
			my $from_int = $network | $server::ip_from;
			my $to_int   = $network | $server::ip_to;
			my $ip_int   = ip::to_int $peer_ip;

			# show edit for clients in our dhcp range
 			if ( $ip_int >= $from_int && $ip_int <= $to_int ) {
				$ip = $peer_ip;
			}
		}

		if ( $ip && $ip ne $server::ip ) {

			my @editable = ( qw/hostname config homepage/ );

			client::conf( $ip, $_ => $param->{$_} ) foreach @editable;

			my $conf = client::all_conf( $ip );
			my $config = delete $conf->{config};

			my $nmap = qq|<a href=/nmap?scan=$ip>nmap</a>|;
			my @table = (
				'ping' => ping::host($ip)
					? qq|<span style="color:green">up</span> $nmap|
					: qq|<span style="color: red">down</span> <a href=/wol/$ip>wol</a> $nmap|
					,
				'ip' => qq|<input type=text name=change_ip value="$ip" onChange="document.getElementById('old_ip').style.display = '';"><span id=old_ip style="display: none; color: #888;">old: $ip<span>|,
				'mac' => format::mac( delete $conf->{mac}, 'html' ),
				'hostname' => qq|<input type=text name=hostname value="| . delete($conf->{hostname}) . qq|">|,
				'config' => html::select( 'config', $config, config::available ),
				html::conf( $ip, $conf, 'edit', @editable )
			);

			print $client ok
				, qq|<form method=get>|
				, html::table( 2, @table ),
				, qq|
					<input type=submit name=action value=change>
					<input type=submit name=action value=remove style="color: red">
					</form>|
				;

			if ( $config ) {
				if ( my $for_ip = config::for_ip( $ip ) ) {
					print $client qq|<h2>config::for_ip</h2>| . html::pre( $for_ip );
				}
			}

			if ( $conf->{amt} ) {
				print $client qq|<h2>amt network</h2>|, html::pre_dump( amt::network( $ip ) );
				print $client qq|<h2>amt log</h2>|, html::pre_dump( amt::log( $ip ) );
			}

		} else {

			print $client ok qq|<h2>Clients on $server::ip</h2>|;

			my @ping;
			if ( my $host = $param->{ping_target} ) {
				@ping = ( $host );
			} elsif ( $param->{ping} ) {
				@ping = client::all_ips;
			}

			my $ping = ping::fping( @ping ) if @ping;
			my $arp = client::arp_mac_dev;

			my @clients;

			foreach my $ip ( client::all_ips ) {
				
				my $conf = client::all_conf( $ip );
				my $mac = delete $conf->{mac} || '';
				my $dev = $arp->{$mac};

 				next unless $dev || $param->{all};

				my $style
					= 'style="color:'
					. ( $ping->{$ip} ? 'green' : 'red' )
					. '"'
					if $ping;

				$style ||= '';
				my $ip_text = qq|<tt>$ip</tt>|;
				$ip_text = qq|<tt><b>$ip</b></tt>| if ip::in_dhcp_range($ip);

				$dev = qq|<tt>$dev</tt>| if $dev;

				push @clients
					, qq|<a $style name=$ip target=client href=/client/$ip>$ip_text</a>|
					, format::mac( $mac => 'html' )
					, $dev
					, delete $conf->{hostname}
					, html::conf( $ip, $conf, 'inline' )
				;
			}

			my $all = $param->{all} ? 0 : 1;

			print $client html::table( -5, 'ip', 'mac', qq|<a href="?all=$all">dev</a>|, 'hostname', 'conf', @clients );
			print $client qq|
				<form method=get>
				<input type=text   name=ping_target   size=15>
				<input type=submit name=ping value=ping>
				</form>
			|;
		}


	} elsif ( $path =~ m{^/brctl} ) {

		system 'brctl addif virtual ' . $param->{addif} if $param->{addif};
		system 'brctl delif virtual ' . $param->{delif} if $param->{delif};

		my $in_virtual;

		my @table =
			map {
				my @c = split(/\t+/,$_,4);
				if ( $#c == 1 ) {
					$in_virtual->{ $c[1] }++;
					@c = ( '', '', '', $c[1] );
				} else {
					$in_virtual->{ $c[3] }++;
				}
				if ( $c[3] =~ m{\d$} ) {
					$c[3] = qq|<input type=submit name=delif value=$c[3] style="color:red" title="remove $c[3] from bridge">|;
				}
				@c
			} split(/\n/, `brctl show`)
		;

		my @add_ifs = grep { ! $in_virtual->{$_} && $_ ne 'virtual' } ip::devices_up;

		push @table, ( '', '', '', html::select( 'addif', @add_ifs ) . qq|<input type=submit value=add></form>| );

		print $client ok
			, qq|<form>|
			, html::table( -4, @table )
			, qq|</form>|
			;


	} elsif ( $path =~ m{^/ip/?(\w+)?} ) {
		print $client ok
			, join("\n", map { qq|<a href=/ip/$_>$_</a>| } ( qw/link addr route neigh ntable tunnel maddr mroute xfrm/ ))
			, ip::html( $1 )
			;
	} elsif ( $path =~ m{^/nmap} ) {
		if ( my $scan = $param->{scan} ) {
			nmap::scan( $scan );
			print $client redirect("$url/client#$scan");
		} else {
			print $client ok, qq|
				<form method=get>
				<input type=text name=scan>
				<input type=submit value=scan>
				</form>
			|;
		}
	} elsif ( $path =~ m{^/wol/(\S+)} ) {
		print $client redirect( "$url/client/$1" ), wol::power_on($1);
	} elsif ( $path =~ m!^/amt/(\w+)/$RE{net}{IPv4}{-keep}! ) {
		my ( $run, $ip ) = ( $1, $2 );
		print $client redirect( "$url/client/$ip" ), amt::RemoteControl( $ip, $run );
	} elsif ( $path =~ m{^/our/(\w+)/(\S+)} ) {
		eval 'our $' . $1 . ' = ' . $2;
		warn $@ if $@;
		print $client redirect($url), qq|<big>$1 = $2</big><br>Location: <a href="$url">$url</a>|;
		server::debug( $debug ) if $1 eq 'debug';
	} elsif ( $path =~ m{^/start_stop/(\S+)} ) {
		print $client redirect, daemons::start_stop($1,$param);
	} elsif ( $path =~ m{^/action/([^/]+)/(.+)} ) {
		my ( $package, $method ) = ( $1, $2 );
		$ENV{nr} = $1 if $package =~ s{\.(\d+)$}{};
		$package->$method();
		print $client redirect;
	} elsif ( $path =~ m{^/kill/static/(\d+)} ) {
		print $client redirect;
		kill 1, $1 || kill 9, $2 && warn "killed $1";
	} else {
		print $client "HTTP/1.0 404 $path\r\nConnection: close\r\nContent-type: text/html\r\n\r\n<big>404 $path</big>";
		warn "404 $path";
	}

}

sub start {

	warn 'network ', network::setup();

	daemons::start_stop 'browser', { url => $url };
	daemons::start_stop $_ foreach ( qw/dhcpd tftpd dnsd syslogd/ );
#	daemons::start_stop 'kvm' unless $ENV{DEV}; # skip kvm statup when running on real device

	my $server = IO::Socket::INET->new(
			Proto     => 'tcp',
#			LocalAddr => $server::ip,
			LocalPort => $httpd::port,
			Listen    => SOMAXCONN,
			Reuse     => 1
	) || die "can't start server on $url: $!";

	print "url $url\n";

	syslogd::install_local;
	client::rebuild_mac_links;

	while (1) {
		my $client = $server->accept() || next; # ALARM trickle us
		my $request = <$client>;

		my $headers;

		while ( my $header = <$client> ) {
			chomp $header;
			last if $header =~ m{^\s*$};
			my ( $n, $v ) = split(/:\s*/, $header);
			$headers->{ lc $n } = $v;
		}

		if ( my $host = $headers->{host} ) {
			$url = 'http://' . $host;
			$url .= ":$port" unless $url =~ m{:\d+$};
		}

		warn "## $url ## $request", dump( $headers ) if $debug;

		if ($request =~ m{^GET (/.*) HTTP/1.[01]}) {
			my $path = $1;
			$path =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge;
			my $param;
			if ( $path =~ s{\?(.+)}{} ) {
				foreach my $p ( split(/[&;]/, $1) ) {
					my ($n,$v) = split(/=/, $p, 2);
					$param->{$n} = $v;
				}
				warn "param: ",dump( $param ) if $debug;
			}
			get_request $client, $path, $param;
		} else {
			print $client "HTTP/1.0 500 No method\r\nConnection: close\r\nContent-type: text/plain\r\n\r\n500 $request";
			warn "500 $request";
		}

		print $client menu() . html_end() if $client->connected;

	}

	die "server died";
}

warn "loaded";

1;
