#!/usr/bin/perl -w
use strict;
use Net::SSH qw(ssh ssh_cmd);

my $cephdir = '/etc/ceph';

my %node =
  (
   mini  => {
	     name   => 'mini',
	     ip     => '10.64.79.122',
	     mon_id => 1,
	     osd_id => 0,
	    },
   tiny  => {
	     name   => 'tiny',
	     ip     => '10.64.79.123',
	     mon_id => 2,
	     osd_id => 1,
	    },
   # server0 => {
   # 	       name   => 'server0',
   # 	       ip     => '10.64.79.7',
   # 	       mon_id => 3,
   # 	       osd_id => 2,
   # 	       offline => 1,
   # 	      },
   ogion => {
	     name   => 'ogion',
	     ip     => '10.64.79.64',
	     mon_id => 4,
	     osd_id => 3,
	    },
  );

my %keyring = (
	       'client.admin' => "${cephdir}/ceph.client.admin.keyring",
	       'mon'          => "${cephdir}/ceph.mon.keyring",
	      );

# generate client.admin keyring
$cmd = join(' ',split($/, qq(
	  ceph-authtool  $keyring{'client.admin'}
	    --create-keyring
	    --gen-key
	    -n client.admin
	    --cap mon 'allow *'
	    --cap osd 'allow *'
	    --cap mds 'allow'
    )));
my $output = qx($cmd);

# generate mon keyring
$cmd = join(' ',split($/, qq(
	ceph-authtool $keyring{mon}
	  --create-keyring
	  --gen-key
	  -n mon.
	  --cap mon 'allow *'
       )));
$output = qx($cmd);

# Import client.admin into mon
$cmd = join(' ',split($/, qq(
	ceph-authtool $keyring{'mon'}
	  --import-keyring $keyring{'client.admin'}
    )));
$output = qx($cmd);
print $ouput if $?;

# Generate the monmap
my $add_str = join(' ', map { exists $_->{offline} ? "" : "--add $_->{mon_id} $_->{ip}" } values %node);

$output = qx(
    monmaptool --create $add_str --clobber --fsid 37ff2273-d55b-48ca-9e5e-89a2951c8197 /tmp/monmap
    );


while( my( $name, $node ) = each ( %node ) ){
  next if exists $node->{offline};

  my $mondir = "/srv/ceph/mon$node->{mon_id}";

  # copy ssh and ceph configs to member nodes
  qx(rsync -avue ssh ~/.ssh/config ${name}:.ssh);
  qx(rsync -avue ssh ~/.ssh/config cjac\@${name}:.ssh);
  qx(rsync -avue ssh ${cephdir}/. ${name}:${cephdir}/);

  my @cmd =(
	    qq(systemctl stop ceph),
	    qq(rm -rf  ${mondir}/*),
	    join(' ',split($/,qq(
	    /usr/bin/ceph-mon
	      -f
	      --mkfs
	      --cluster ceph
	      --id $node->{mon_id}
	      --monmap ${cephdir}/monmap
	      --keyring $keyring{mon}
	      --setuser ceph
	      --setgroup ceph
            ))),
	    qq(systemctl start ceph)
	   );
  foreach my $cmd ( @cmd ){
    ssh_cmd( "root\@$name", $cmd );
  }
}

