#!/usr/bin/php
<?php
// Please change these parameters
$subnetid = 'subnet-08d5fcb424f826e37';
$securitygpid = 'sg-0a33a6aeffeae8334';
$aim = 'ami-064bd75d207f71bf4';
$computetype = 't2.micro';
$compute_slots = 1;
$previsiontime = 60;          // in seconds

// get master host name and IP
$masterhostname = gethostname();
$masterip = gethostbyname($masterhostname);
$masterhostname = substr($masterhostname, 0,
                         strpos($masterhostname, '.', 0));

$dbfile = '/tmp/.aip_aws.db';

// Check input parameters
if ($argc < 2 || ($numneeded = intval($argv[1])) < 1) {
    echo("Usage: ".$argv[0]." number_of_slots\n");
    exit(1);
}

$numhosts = intval($numneeded / $compute_slots) +
            ($numneeded % $compute_slots > 0 ? 1 : 0);

// launch instances
$output = shell_exec("aws ec2 run-instances --image-id=".$aim.
                     " --security-group-ids ".$securitygpid.
                     " --subnet-id ".$subnetid.
                     " --no-associate-public-ip-address ".
                     " --count ".$numhosts.
                     " --instance-type ".$computetype);
$new_inst = json_decode($output, true);
// check error
if ($new_inst === FALSE) {
    printf("Error: %s\n", $output);
    exit(1);
}

// read dbfile
$instances = [];
if (file_exists($dbfile)) {
    $instances = json_decode(file_get_contents($dbfile));
    if ($instances === FALSE)
        $instances = [];
}

// update dbfile
$instances = array_merge($instances, $new_inst['Instances']);
file_put_contents($dbfile, json_encode($instances));

// wait for the
sleep($previsiontime);

// read master cb.yaml
$aip_conf = yaml_parse_file('/opt/skyformai/etc/cb.yaml');

// set up cb.yaml and hosts file for new instances
foreach ($new_inst['Instances'] as $inst) {
    $inst_ip = $inst['PrivateIpAddress'];
    // AWS has the rule of naming a host and the host is
    // reachable via AWS internal DNS
    $inst_hostname = 'ip-'.str_replace('.', '-', $inst_ip);
    shell_exec('scp -o StrictHostKeyChecking=no /opt/skyformai/etc/cb.yaml root@'.
               $inst_ip.':/opt/skyformai/etc/');
    file_put_contents("/tmp/hosts",
                      $inst_ip." ".$inst_hostname."\n".
                      $masterip." ".$masterhostname."\n");
    shell_exec('scp /tmp/hosts root@'.$inst_ip.
               ':/opt/skyformai/etc/');
    // add new host into $aip_conf
    $aip_conf['cluster']['hosts'][] = ['name'=>$inst_hostname];
    yaml_emit_file('/tmp/cb.yaml', $aip_conf);
    shell_exec('scp /tmp/cb.yaml root@'.$inst_ip.
               ':/opt/skyformai/etc/');
    shell_exec('ssh root@'.$inst_ip.' service aip restart');
    shell_exec('source /etc/profile.d/aip.sh;caddhost -M '.
                $compute_slots.' '.$inst_hostname);
    sleep(10);
}
?>
