#!/usr/bin/php
<?php
// Please change these parameters
$domain="";
$username="";
$password="";
$region="cn-north-4";
$project_id="0eeedd404180f3f52fd2c00776c16d96";
$enterprise_project_id="b59aae71-7544-4552-9042-2d3fc94d9045";
$flavor="c7.large.2";
$image="c18bd59c-40c0-4600-849c-0af2f7fca745";
$vpcid="d21a0f47-a66b-44a4-b61e-3ea3e1b505db";
$subnet_id="f3a949a8-9b9b-470f-9276-da844bc82e3a";
$admin_pass="P@ssw0rd";
$volume_type="SSD";
$volume_size=40;
$compute_slots=1;
$provisiontime=120;          // in seconds

// get master host name and IP
$masterhostname = gethostname();
printf("masterhostname: %s\n", $masterhostname);
$masterip = gethostbyname($masterhostname);
printf("masterip: %s\n", $masterip);

$dbfileHost = '/tmp/.aip_huawei_host.db';

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

// provision number of hosts
$numhosts = intval($numneeded / $compute_slots) +
            ($numneeded % $compute_slots > 0 ? 1 : 0);
printf("numhosts: %s\n", $numhosts);

// hostname="aip-compute-$now"
date_default_timezone_set('Asia/Shanghai');
$time=date("Ymd-His");

putenv('PATH='.getenv('PATH').':/usr/local/bin');
putenv('USER=cadmin');
putenv('HOME=/share/home/cadmin');

// launch instances
$createservers_cmd = "hcloud ECS CreateServers --cli-domain=".$domain.
                     " --cli-username=\"".$username."\"".
                     " --cli-password=\"".$password."\"".
                     " --cli-region=".$region.
                     " --project_id=".$project_id.
                     " --server.extendparam.enterprise_project_id=".$enterprise_project_id.
                     " --server.flavorRef=".$flavor.
                     " --server.imageRef=".$image.
                     " --server.vpcid=".$vpcid.
                     " --server.nics.1.subnet_id=".$subnet_id.
                     " --server.root_volume.volumetype=".$volume_type.
                     " --server.root_volume.size=".$volume_size.
                     " --server.count=".$numhosts.
                     " --server.name=hw-hpc-compute-".$time.
                     " --server.adminPass=".$admin_pass;
printf("createservers_cmd: %s\n", $createservers_cmd);
$output = shell_exec($createservers_cmd);
printf("output: %s\n", $output);
$new_inst = json_decode($output, true);
// check error
if ($new_inst === FALSE) {
    printf("Error: %s\n", $output);
    exit(1);
}

// wait for the vm provisioning
sleep($provisiontime);

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

$aip_host_file = '/tmp/.aip_huawei_aip_hosts';
if (!file_exists($aip_host_file)) {
    shell_exec('yes | cp /etc/hosts '.$aip_host_file);
}

$count=0;
foreach ($new_inst['serverIds'] as $inst) {
    // query server
    $showserver_cmd = "hcloud ECS ShowServer --cli-domain=".$domain.
                         " --cli-username=".$username.
                         " --cli-password=".$password.
                         " --cli-region=".$region.
                         " --project_id=".$project_id.
                         " --server_id=".$inst;
    printf("showserver_cmd: %s\n", $showserver_cmd);
    $output = shell_exec($showserver_cmd);
    $new_inst = json_decode($output, true);
    // check error
    if ($new_inst === FALSE) {
        printf("Error: %s\n", $output);
        exit(1);
    }
    $inst_status = $new_inst['server']['status'];
    printf("inst_status: %s\n", $inst_status);
    if ($inst_status != "ACTIVE") {
        $count++;
        if ($count > 10) {
            printf("Error: %s status not active", $inst);
            exit(1);
        }
        continue;
    }
    $inst_hostname = $new_inst['server']['name'];
    printf("inst_hostname: %s\n", $inst_hostname);

    // query interface
    $interfaces_cmd = "hcloud ECS ListServerInterfaces --cli-domain=".$domain.
                         " --cli-username=".$username.
                         " --cli-password=".$password.
                         " --cli-region=".$region.
                         " --project_id=".$project_id.
                         " --server_id=".$inst;
    printf("interfaces_cmd: %s\n", $interfaces_cmd);
    $output = shell_exec($interfaces_cmd);
    $new_inst = json_decode($output, true);
    // check error
    if ($new_inst === FALSE) {
        printf("Error: %s\n", $output);
        exit(1);
    }
    $inst_ip = $new_inst['interfaceAttachments'][0]['fixed_ips'][0]['ip_address'];
    printf("inst_ip: %s\n", $inst_ip);

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

    // update dbfileHost
    $new_host = '{"server_id":"'.$inst.'", "server_name":"'.$inst_hostname.'", "ip_address":"'.$inst_ip.'"}';
    printf("new_host: %s\n", $new_host);
    array_push($instances, $new_host);
    file_put_contents($dbfileHost, json_encode($instances));
    
    // update aip hosts file
    shell_exec('echo '.$inst_ip.' '.$inst_hostname.' >> '.$aip_host_file);
               
    // set hostname
    shell_exec('sudo ssh root@'.$inst_ip.' "hostnamectl set-hostname '.$inst_hostname.'"');
    
    // add dynamic host
    shell_exec('source /etc/profile.d/aip.sh;caddhost -M '.$compute_slots.
               ' -a '.$inst_ip.' '.$inst_hostname); 

    // mount -t nfs -o vers=3,nolock 10.111.16.143:/ /share/
    shell_exec('sudo ssh root@'.$inst_ip.' "mount -t nfs -o vers=3,nolock 10.111.16.143:/ /share/"');          
               
    // copy hosts/cb.yaml from master to compute
    file_put_contents("/tmp/hosts",
                      $inst_ip." ".$inst_hostname."\n".
                      $masterip." ".$masterhostname."\n");
    shell_exec('sudo 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('sudo scp /tmp/cb.yaml root@'.$inst_ip.
               ':/opt/skyformai/etc/');

    // restart compute aip
    shell_exec('sudo ssh root@'.$inst_ip.' "source /etc/profile.d/aip.sh; systemctl stop aip; sleep 1; systemctl start aip"');

    sleep(10);
}

// update all aip host /etc/hosts
$output=shell_exec("cat ".$aip_host_file."|awk '{ print $1 }'");
$lines = explode("\n", $output);
foreach ($lines as $host) {
    if (empty($host) || $host === "127.0.0.1" || $host === "::1") {
        continue;
    }
    shell_exec('sudo scp '.$aip_host_file.' root@'.$host.':/etc/hosts');
}
?>
