#!/usr/bin/perl 
# $Id: netexamplix-setup,v 1.4 2007-12-13 00:41:39 jeffbeck Exp $
# Dieses Script (netexamplixix-setup) wurde von Rdiger Beck erstellt
# Es ist freie Software
# Bei Fehlern wenden Sie sich bitte an mich.
# jeffbeck@web.de  oder  jeffbeck@gmx.de

# netexamplixix-setup configures netexamplix on
# a sophomorix2-system
# It should be run as postinst
use strict;
use DBI;
use Getopt::Long;
Getopt::Long::Configure ("bundling");

my$help=0;

my $server="localhost";

my $group_to_add="netexamplix";
my $user_to_add="netexamplix";
my $localcvs=0;


# Parsen der Optionen
my $testopt=GetOptions(
           "verbose|v+" => \$Conf::log_level,
           "help|h" => \$help,
           "localcvs" => \$localcvs,
          );


# Prfen, ob Optionen erkannt wurden
#&check_options($testopt);

if ($localcvs==0){
    print "\nIf you want to configure a local cvs-server\n";
    print "  Run the script:\n";
    print "  netexamplix-setup --localcvs\n\n";
    print "\nIf you want to configure a remote cvs-server\n";
    print "  do the following:\n";
    print "  ...\n\n";
}


# local CVS access
if ($localcvs==1){
   # 1) create group netexamplix
   my ($group)=getgrnam($group_to_add);
   if (not defined $group){
       print "Group $group_to_add must be added!\n";
       # ??? check if user is in correct group
       system("groupadd $group_to_add");
   } else {
       print "Group $group_to_add exists already. Doing nothing!\n";
   }

   # 2) create user netexamplix 

   my ($name)=getpwnam($user_to_add);
   if (not defined $name){
       print "User $user_to_add must be added!\n";
       # ??? check if user is in correct group
       system("useradd -m -g $group_to_add $user_to_add");
   } else {
       print "User $user_to_add exists already. Doing nothing!\n";
   }


   # 3) set a complicated password 
   # (password will not not be used, login will be with sshkey)

   my $password = int( rand(9999999999)) + 9999999999;
   system("usermod -p $password $user_to_add");

   # 4) create a repository for the group netexamplix

   system("mkdir -p /var/lib/cvs-netexamplix");
   system("chgrp netexamplix /var/lib/cvs-netexamplix");
   system("chmod 2770 /var/lib/cvs-netexamplix");
   system("cvs -d /var/lib/cvs-netexamplix init");

   # check if user netexamplix is the only user in this group

   # 5) generate a sshkey for the user root, so that she can 
   #    access the repository as user netexamplix 
   my $key_dsa="/root/.ssh/netexamplix_key_dsa";

   # generate key
   print "Generating a key ...\n";
   system("/usr/bin/ssh-keygen -f ${key_dsa} -t dsa -N ''");
   system("/bin/chmod 0600 ${key_dsa}.pub");

   # copy key
   print "Copying public key to other server...\n";
   my $command="ssh-copy-id -i ${key_dsa}.pub ${user_to_add}\@${server}";
   print "$command\n";
   system("$command");
}
