#!/usr/bin/perl
use strict;
use FindBin qw($Bin);
use lib $Bin;
use onserver;

setup();

my $gitbase = "$scriptsdir/git";
my $htpasswd = "$gitbase/$addrend.git/.htpasswd";

open HTACCESS, ">.htaccess";
print HTACCESS <<EOF;
RewriteEngine On

RewriteCond %{QUERY_STRING} =service=git-receive-pack [OR]
RewriteCond %{REQUEST_URI} /git-receive-pack\$
RewriteRule ^($addrend\\.git/.*)\$ /~$USER/$addrend/_git-auth.cgi/\$1
<Files _git-auth.cgi>
    AuthName "Git Access"
    AuthType basic
    AuthUserFile $htpasswd
    Require user $admin_username

    # Alternatively, replace "require user" with:
    #Require group somegroup
    #AuthGroupFile $gitbase/$addrend/.htgroup
    # and set up .htgroup appropriately
</Files>

RewriteRule ^($addrend\\.git/.*)\$ /~$USER/$addrend/_git.cgi/\$1
EOF
close HTACCESS;
chmod 0777, ".htaccess";

open GIT_CGI, ">_git.cgi";
print GIT_CGI <<EOF;
#!/bin/sh
case "\$PATH_INFO" in
    .. | ../* | */.. | */../*)
        echo "Content-type: text/plain"
        echo "Status: 403 Forbidden"
        echo ""
        echo "Error: Illegally found '..' in PATH_INFO='\$PATH_INFO'"
        echo "gitautoinstaller: \$HOME: found '..' in PATH_INFO='\$PATH_INFO'" >&2
        exit 1;;
    /$addrend.git/*)
        # pass
        ;;
    *)
        echo "Content-type: text/plain"
        echo "Status: 403 Forbidden"
        echo ""
        echo "Error: PATH_INFO='\$PATH_INFO' must start with /$addrend.git/"
        echo "gitautoinstaller: \$HOME: found bad start in PATH_INFO='\$PATH_INFO'" >&2
        exit 1;;
esac
export GIT_PROJECT_ROOT="$gitbase"
export PATH_TRANSLATED="\$GIT_PROJECT_ROOT\$PATH_INFO"
exec git http-backend
EOF
close GIT_CGI;
chmod 0755, "_git.cgi";
symlink "_git.cgi","_git-auth.cgi";

chdir $gitbase;
system qw{git init --bare}, "$addrend.git";
chdir "$addrend.git";

open ENABLE, ">git-daemon-export-ok";
print ENABLE "";
close ENABLE;

system qw{htpasswd -c}, $htpasswd, $admin_username;

print "Your git repository is located in:\n";
print "  $gitbase/$addrend.git/\n";
print "To clone, run\n  git clone https://$USER.scripts.mit.edu/$addrend/$addrend.git\n\n";
press_enter;

exit 0;
