#!/usr/bin/perl

# INTERNAL COMMAND.  NOT MEANT TO BE RUN BY THE USER DIRECTLY.

# sets up REPO_BASE, GL_ADMINDIR.  Symlinks hooks

use strict;
use warnings;

# ----------------------------------------------------------------------------
#       find the rc file, then pull the libraries
# ----------------------------------------------------------------------------

BEGIN {
    die "ENV GL_RC not set\n"     unless $ENV{GL_RC};
    die "ENV GL_BINDIR not set\n" unless $ENV{GL_BINDIR};
}

use lib $ENV{GL_BINDIR};

use gitolite_rc;
use gitolite_env;
use gitolite;

setup_environment();

# mkdir $REPO_BASE, $GL_ADMINDIR if they don't already exist
wrap_mkdir($REPO_BASE);
wrap_mkdir( $GL_ADMINDIR, 0700 );

# mkdir $GL_ADMINDIR's subdirs
for my $dir (qw(conf keydir logs hooks hooks/common hooks/gitolite-admin)) {
    wrap_mkdir( "$GL_ADMINDIR/$dir", 0700 );
}

# hooks must be propagated to all the repos in case they changed

# See http://sitaramc.github.com/gitolite/hook_prop.html if you're not sure
# what is happening here, especially the picture toward the end.

# all repos, all hooks
chdir($REPO_BASE) or die "chdir $REPO_BASE failed: $!\n";
for my $repo (`find . -type d -name "*.git" -prune`) {
    chomp($repo);
    # propagate user hooks
    ln_sf( "$GL_ADMINDIR/hooks/common", "*", "$repo/hooks" );
    # propagate package hooks, overriding user hooks
    ln_sf( "$GL_PACKAGE_HOOKS/common", "*", "$repo/hooks" );
    foreach(glob "$repo/hooks/*") { -l && ! -e && unlink};
    chmod 0755, "$repo/hooks/update";
}

# (special!) gitolite-admin repo, post-update hook, package hook only
if ( -d "gitolite-admin.git/hooks" ) {
    ln_sf( "$GL_PACKAGE_HOOKS/gitolite-admin", "post-update", "gitolite-admin.git/hooks" );
    chmod 0755, "gitolite-admin.git/hooks/post-update";
}

# deal with old program names...
# not needed for RPM/DEB type systems since they take care of it themselves
# but people upgrading might appreciate this; not sure how useful it is though
for my $oldname (qw(pta-hook.sh conf-convert.pl 00-easy-install.sh gl-easy-install 99-emergency-addkey.sh gl-emergency-addkey install.pl update-hook.pl hooks/update ga-post-update-hook VERSION)) {
    unlink "$GL_ADMINDIR/src/$oldname";
    unlink "$ENV{HOME}/gitolite-install/src/$oldname";
}
