#!/usr/bin/perl
package IkiWiki::Plugin::gitpush;

use warnings;
use strict;
use IkiWiki 3.00;

sub import {
	hook(type => "getsetup", id => "gitpush", call => \&getsetup);
	hook(type => "refresh", id => "gitpush", call => \&refresh);
	hook(type => "savestate", id => "gitpush", call => \&savestate);
}

sub getsetup () {
	my $keyurl=length $config{cgiurl} ? IkiWiki::cgiurl(do => "sshkey") : "";
	return
		plugin => {
			safe => 1,
			rebuild => 0,
			section => "core",
		},
		git_push_to => {
			type => "string",
			example => [],
			description => "git repository urls that changes are pushed to",
			htmldescription => "git repository urls that changes are pushed to (using <a href=\"$keyurl\">this ssh key</a>)",
			safe => 1,
			rebuild => 0,
		},
}

# Pushing is deferred to the end to avoid running at the same time
# as site building.
my $need_push;

sub refresh {
	$need_push=1;
}

sub savestate {
	if ($need_push && $config{rcs} eq 'git' &&
	    ref($config{git_push_to}) eq 'ARRAY' &&
	    scalar @{$config{git_push_to}}) {
		# daemonise
		defined(my $pid = fork) or error("Can't fork: $!");
		return if $pid;
		chdir '/';
		open STDIN, '/dev/null';
		open STDOUT, '>/dev/null';
		POSIX::setsid() or error("Can't start a new session: $!");
		open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
		
		# Don't need to keep a lock on the wiki as a daemon.
		IkiWiki::unlockwiki();
		
		# Low priority job.
		eval q{use POSIX; POSIX::nice(10)};
		
		# Ensure we have a ssh key generated to use.
		IkiWiki::Plugin::ikiwikihosting::get_ssh_public_key();
		# Avoid ssh host key checking prompts.
		$ENV{GIT_SSH}="iki-ssh-unsafe";

		chdir "$ENV{HOME}/source.git/" || die $!;

		foreach my $url (@{$config{git_push_to}}) {
			next unless length $url;

			system('git', 'push', '--quiet', '--mirror', $url);
		}

		exit 0;
	}
}

1
