<?php

require_once __DIR__ . '/../init.php';

global $globalConfig;

$CloudFlareConfig = $globalConfig['cloudflare'];

try {
    $key = new Cloudflare\API\Auth\APIKey($CloudFlareConfig['email'], $CloudFlareConfig['api_keys']);

    $adapter = new Cloudflare\API\Adapter\Guzzle($key);

    $zones = new Cloudflare\API\Endpoints\Zones($adapter);

    $zoneID = $zones->getZoneID($CloudFlareConfig['base_domain']);

    $dns = new Cloudflare\API\Endpoints\DNS($adapter);

    $records = $dns->listRecords($zoneID, 'A', $CloudFlareConfig['secondary_domain']);

    $recordId = $records->result[0]->id;

    $recordIp = $records->result[0]->content;

} catch (Exception $e) {
    logMessage('ERROR', $e->getMessage());
    die;
}


$realIp = shell_exec('curl -s ip.sb');
$realIp = str_replace("\n", "", $realIp);

if (!empty($realIp)) {
    if ($realIp !== $recordIp) {
        $msg = 'ip changed from ' . $recordIp . ' to ' . $realIp;

        $details = [
            'type' => 'A',
            'name' => $CloudFlareConfig['secondary_domain'],
            'content' => $realIp
        ];

        try {
            $dns->updateRecordDetails($zoneID, $recordId, $details);

            $url = 'https://sc.ftqq.com/' . $globalConfig['serverchan_token'] . '.send';

            $client = new \GuzzleHttp\Client();
            $client->request('POST', $url, [
                'text' => 'IP变更',
                'desc' => $msg,
            ]);
//            $cmd = <<< CMD
//curl -s 'https://oapi.dingtalk.com/robot/send?access_token={$globalConfig['dingtalk_token']}' -H 'Content-Type: application/json' -d "{\"msgtype\": \"text\",\"text\": {\"content\": \"$msg\"}}"
//CMD;
//            shell_exec($cmd);

            logMessage('SUCCESS', $msg);
        } catch (Exception $e) {
            logMessage('ERROR', $e->getMessage());
        }
    } else {
        logMessage('VOID', 'ip same');
    }
} else {
    logMessage('ERROR', 'get real ip fail');
}


function sc_send($text, $desp = '', $key = 'SCU159053T3de1450d55d3b894e39c7a2ecd583984601fce6865119')
{
    $postdata = http_build_query(
        array(
            'text' => $text,
            'desp' => $desp
        )
    );

    $opts = array('http' =>
        array(
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata
        )
    );
    $context = stream_context_create($opts);
    return $result = file_get_contents('https://sc.ftqq.com/' . $key . '.send', false, $context);

}


function logMessage($type, $msg = '')
{
    echo date('Y-m-d H:i:s') . ' ' . $type . ': ' . $msg . PHP_EOL;
}