#!/usr/bin/php
<?php

declare(strict_types=1);

$pushover_url = (isset($_SERVER['PUSHOVER_URL']) && strlen($_SERVER['PUSHOVER_URL']) > 0 ? $_SERVER['PUSHOVER_URL'] : 'https://api.pushover.net/1/messages.json');

// Only run from the command line
if (php_sapi_name() !== 'cli') {
    fprintf(STDERR, "This script can only be ran from the command line\n");
    exit(1);
}
error_reporting(E_ALL);
set_time_limit(0);

// Check environment
$keys = [
    'SMARTD_SUBJECT',
    'SMARTD_FULLMESSAGE',
    'APP_TOKEN',
    'USER_TOKEN',
];
$missing = false;
foreach ($keys as $key) {
    if (!array_key_exists($key, $_SERVER) || strlen($_SERVER[$key]) === 0) {
        $missing = true;
        fprintf(STDERR, "Missing environment variable %s\n", $key);
    }
}
if ($missing) {
    exit(1);
}

// Initialize curl
$ch = curl_init();
if ($ch === false) {
    fprintf(STDERR, "Failed to initialize curl\n");
    exit(1);
}

$cv = curl_version();
$useragent = "curl/{$cv['version']}";

$fields = [
    'user'=>$_SERVER['USER_TOKEN'],
    'token'=>$_SERVER['APP_TOKEN'],
    'title'=>$_SERVER['SMARTD_SUBJECT'],
    'message'=>$_SERVER['SMARTD_FULLMESSAGE'],
];
curl_setopt_array($ch, [
    CURLOPT_URL => $pushover_url,
    CURLOPT_POST => count($fields),
    CURLOPT_POSTFIELDS => $fields,
    CURLOPT_HEADER => 0,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_USERAGENT => $useragent,
]);
$result = curl_exec($ch);
unset($ch);

fprintf(STDERR, "Result: %s\n", $result);
