#!/usr/bin/php
<?php
// Please change these parameters
$domain="";
$username="";
$password="";
$region="cn-north-4";
$project_id="0eeedd404180f3f52fd2c00776c16d96";

$dbfile = '/tmp/.aip_huawei_host.db';
$aip_host_file = '/tmp/.aip_huawei_aip_hosts';

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

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

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

$toTerm = [];
$term_hosts = array_slice($argv, 1);
$n = sizeof($instances);
for($i = 0; $i < $n; $i++) {
    $inst = json_decode($instances[$i], true);
    $inst_hostname = $inst['server_name'];
    $inst_ip = $inst['ip_address'];
    if (in_array($inst_hostname, $term_hosts)) {
        $toTerm[] = $inst['server_id'];
        unset($instances[$i]);
        shell_exec('source /etc/profile.d/aip.sh;crmhost '.$inst_hostname);
        shell_exec("sed -i '/".$inst_hostname."/d' ".$aip_host_file);
    }
}
if (sizeof($toTerm) > 0) {
    $n = sizeof($toTerm);
    for($i = 0; $i < $n; $i++) {
        // delete server
        $deleteserver_cmd = "hcloud ECS DeleteServers --cli-domain=".$domain.
                             " --cli-username=".$username.
                             " --cli-password=".$password.
                             " --cli-region=".$region.
                             " --project_id=".$project_id.
                             " --servers.1.id=".$toTerm[$i];
        printf("deleteserver_cmd: %s\n", $deleteserver_cmd);
        $output = shell_exec($deleteserver_cmd);
        printf("output: %s\n", $output);
    }
    file_put_contents($dbfile, json_encode(array_values($instances)));
}
?>