<?php

/**
 * 执行方法
 * php scripts/generate_auth_signature.php
 * php scripts/generate_auth_signature.php 设备码 密钥 时间戳
 * php scripts/generate_auth_signature.php 1 564d14asdasd113e46542asd6das1a2a
 */
declare(strict_types=1);

$deviceId = $argv[1] ?? '1';
$secret = $argv[2] ?? ((string) getenv('AUTH_TOKEN_SECRET') ?: '564d14asdasd113e46542asd6das1a2a');
$timestamp = $argv[3] ?? (string) time();

$params = [
    'device_id' => (string) $deviceId,
    'secret' => (string) $secret,
    'timestamp' => (string) $timestamp,
];

ksort($params);

$pairs = [];
foreach ($params as $key => $value) {
    $pairs[] = $key . '=' . $value;
}

$plain = implode('&', $pairs);
$signature = strtoupper(md5($plain));

echo 'device_id: ' . $params['device_id'] . PHP_EOL;
echo 'secret: ' . $params['secret'] . PHP_EOL;
echo 'timestamp: ' . $params['timestamp'] . PHP_EOL;
echo 'signature: ' . $signature . PHP_EOL;
echo 'url: /api/v1/authToken?secret=' . rawurlencode($params['secret']) . '&timestamp=' . rawurlencode($params['timestamp']) . '&device_id=' . rawurlencode($params['device_id']) . '&signature=' . rawurlencode($signature) . PHP_EOL;

