package Modules::Scponly;

BEGIN {
  use Exporter;
  @ISA = ('Exporter');
  @EXPORT=qw( &CreateRoot );

  $class="Modules::Scponly";
}

use File::Find;
use File::stat;
use User::pwent;

my $msgError;

sub LastError {
  return $msgError;
}

sub CreateRoot {
  my $account = shift;
  my $chroot = shift;
  unless ($account && -d $chroot){
    $msgError = "Bad argumnets";
    return 0;
  }

  my ($pwAcc,$home,$stHome,$stChroot);
  unless(  $pwAcc = getpwnam($account)){
    $msgError = "No user: $account";
    return 0;
  }
  $home = $pwAcc->dir;
  unless (-d $home){
    $msgError = "No directory: $home";
    return 0;
  }

  unless (stat($home)->dev == stat($chroot)->dev) {
    $msgError = "Devices are different";
    return 0;
  }

# make tree
  find sub { if(-d && ($File::Find::name =~/^$chroot(.+)/)){ &makeDir("$home$1")} },  $chroot;

#make links
  find sub { if((-f || -l) && ($File::Find::name =~ /^$chroot(.+)/)){ &makeLink($1,$chroot,$home)} }, $chroot;

  my $sshDir="$home/.ssh";
  &makeDir( $sshDir );
  chown 0,0, $sshDir;

  if ( open( PASSWD, '< /etc/passwd' ) ) {
		my $re = qr/^\Q$account\E:/;
    my @passwd = grep { /$re/ } ( <PASSWD> );
    close (PASSWD);
    if ( @passwd ) {
			$passwd = "$home/etc/passwd";
      if ( open( PASSWD, '>', $passwd ) ) {
				print PASSWD @passwd;
				close ( PASSWD );
				chmod 0644, $passwd;
      } else {
				$msgError = "Can not create file: $passwd ($!)";
				return 0;
      }
    }else{
      $msgError="Bad account: $account";
      return 0;
    }
  }else{
    $msgError="Can not open /etc/passwd ($!)";
    return 0;
  }

  my $grp = $::userGroup || 'ftponly';
  if ( open( GROUP, '< /etc/group' ) ) {

		my $re = qr/^(\Q$grp\E|\Q$account\E):/; ## to find ftponly & web<N>

    my @group = grep { /$re/ } (<GROUP>); ## select lines
    close ( GROUP );

    if ( @group ) {
			my $group = "$home/etc/group";
      if ( open ( GROUP, '>', $group ) ) {
				print GROUP @group;
				close (GROUP);
				chmod 0644, $group;
      } else {
				$msgError = "Can not create file: $group ($!)";
				return 0;
      }
    }else{
      $msgError = "Bad group: $grp";
      return 0;
    }
  }else{
    $msgError = "Can not open /etc/group ($!)";
    return 0;
  }


  $msgError = undef;
  return 1;
}

sub makeDir{
  my $path = shift;
  my $mode = shift;
  unless( -d $path ) {
    mkdir $path;
  }
  if ( $mode ) {
    chmod $mode,$path;
  }
}

sub makeLink{
  my($file,$fromDir,$toDir)=@_;
  my $fromFile = "$fromDir$file";
  my $toFile = "$toDir$file";
  my $srcLink;
  if ( -l $fromFile ) {
    unless ( -l $toFile ) {
      unlink $toFile;
      $srcLink = readlink($fromFile);
      if ( $srcLink ) {
				symlink $srcLink,$toFile;
      }
    }
  } else {
    if ( -f $toFile ) {
      unless ( stat($fromFile)->ino == stat($toFile)->ino ) {
				unlink $toFile;
				link $fromFile,$toFile;
      }
    } else {
      link $fromFile,$toFile;
    }
  }
}

1;
