<?php
/**
 * 康之源运维 · 站点升级器（单文件，PHP 7.4+，仅需 curl + zip 扩展）
 *
 * 放在客户站点根目录，重命名为 kzy-upgrade.php，改下面 5 个配置即可。
 *
 * 命令行：
 *   php kzy-upgrade.php status     查看当前版本 / 可用版本
 *   php kzy-upgrade.php apply 1.2.3  向运维申请升级（等运维批准）
 *   php kzy-upgrade.php run        运维批准后执行升级（自动备份 + 覆盖 + 回调结果）
 *   php kzy-upgrade.php rollback   回滚到上一次升级前
 *
 * 网页：浏览器访问 kzy-upgrade.php?token=你的网页口令
 */

// ====================== 配置（改这里） ======================
const KZY_BASE        = 'https://work.cnkzy.cn';   // 运维中心地址
// ★ 只填授权号就够了：运维在授权页点过「开通升级」后，执行
//      php kzy-upgrade.php license LIC20261127018
//   会自动换取 appId / appSecret / siteKey 并写入 .kzy-upgrade.state.json
//   客户完全不用抄密钥（密钥也不会出现在代码里）
const KZY_LICENSE     = '';                        // 授权编号，如 LIC20261127018
const KZY_APP_ID      = 'kzy_xxxxxxxxxxxx';        // 可留占位，由授权号自动换
const KZY_APP_SECRET  = 'xxxxxxxxxxxxxxxx';        // 可留占位，由授权号自动换
const KZY_SITE_KEY    = 'sk_xxxxxxxxxxxxxxxx';     // 可留占位，由授权号自动换
const KZY_WEB_TOKEN   = 'change-me-please';        // 网页访问口令，务必改掉
const KZY_HOOK_AFTER  = '';                        // 升级后执行，如 'php think clear' / 'systemctl reload php-fpm'
const KZY_EXCLUDE     = [                          // 永不被升级包覆盖
    'kzy-upgrade.php', '.kzy_backup', '.kzy_upgrade_tmp', '.env', 'config.php',
];
// ============================================================

class KzyUpgrader
{
    private $root;
    private $tmp;
    private $backup;
    private $appId;
    private $appSecret;
    private $siteKey;
    private $stateFile;

    public function __construct()
    {
        $this->root = rtrim(str_replace('\\', '/', __DIR__), '/');
        $this->tmp = $this->root . '/.kzy_upgrade_tmp';
        $this->backup = $this->root . '/.kzy_backup';
        $this->stateFile = $this->root . '/.kzy-upgrade.state.json';
        $this->appId = KZY_APP_ID;
        $this->appSecret = KZY_APP_SECRET;
        $this->siteKey = KZY_SITE_KEY;
        $this->loadState();
    }

    // ---------- 授权号换取凭据 ----------
    private function isPlaceholder($v)
    {
        return $v === '' || $v === null || strpos($v, 'xxxx') !== false;
    }

    private function loadState()
    {
        if (!is_file($this->stateFile)) return;
        $s = json_decode((string) @file_get_contents($this->stateFile), true);
        if (!is_array($s)) return;
        if (!empty($s['appId'])) $this->appId = $s['appId'];
        if (!empty($s['appSecret'])) $this->appSecret = $s['appSecret'];
        if (!empty($s['siteKey'])) $this->siteKey = $s['siteKey'];
    }

    private function saveState($data)
    {
        $keep = is_file($this->stateFile)
            ? (array) json_decode((string) @file_get_contents($this->stateFile), true) : [];
        @file_put_contents($this->stateFile,
            json_encode(array_merge($keep, $data), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),
            LOCK_EX);
        @chmod($this->stateFile, 0600);
        $this->loadState();
    }

    /** 凭授权号从运维中心换全套接入凭证（免签名接口，靠授权号 + 来源绑定校验） */
    public function provision($licenseNo, $domain = null)
    {
        $payload = ['licenseNo' => $licenseNo];
        if ($domain === null || $domain === '') {
            $domain = PHP_SAPI === 'cli' ? (gethostname() ?: '') : ($_SERVER['HTTP_HOST'] ?? '');
        }
        $payload['domain'] = $domain;
        $payload['stack'] = 'php';
        $payload['rootPath'] = $this->root;
        $body = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $ch = curl_init(KZY_BASE . '/open/v1/upgrade/provision');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_SSL_VERIFYPEER => true,
        ]);
        $resp = curl_exec($ch);
        if ($resp === false) {
            $err = curl_error($ch);
            curl_close($ch);
            throw new RuntimeException('网络请求失败：' . $err);
        }
        curl_close($ch);
        $j = json_decode($resp, true);
        if (!is_array($j)) throw new RuntimeException('返回不是 JSON：' . mb_substr((string) $resp, 0, 200));
        if (($j['code'] ?? -1) != 0) throw new RuntimeException('接入失败：' . ($j['msg'] ?? '未知错误'));
        $d = $j['data'] ?? [];
        $this->saveState([
            'licenseNo' => $d['licenseNo'] ?? $licenseNo,
            'appId' => $d['appId'] ?? '',
            'appSecret' => $d['appSecret'] ?? '',
            'siteKey' => $d['siteKey'] ?? '',
            'siteName' => $d['siteName'] ?? '',
            'productKey' => $d['productKey'] ?? '',
            'expireDate' => $d['expireDate'] ?? '',
            'savedAt' => date('Y-m-d H:i:s'),
        ]);
        return $d;
    }

    /** 任何命令执行前：凭据不全就用授权号自动换一次 */
    private function ensureCredentials()
    {
        if (!$this->isPlaceholder($this->appId) && !$this->isPlaceholder($this->appSecret)
            && !$this->isPlaceholder($this->siteKey)) {
            return;
        }
        if ($this->isPlaceholder(KZY_LICENSE)) {
            throw new RuntimeException(
                "还没接入。两种方式任选：\n" .
                "  1) php kzy-upgrade.php license LIC2026xxxxxx   （推荐，只填授权号）\n" .
                "  2) 直接在文件顶部填 KZY_APP_ID / KZY_APP_SECRET / KZY_SITE_KEY");
        }
        $this->provision(KZY_LICENSE);
    }

    public function ensureCredentialsPublic()
    {
        $this->ensureCredentials();
    }

    public function siteKeyPublic()
    {
        return $this->siteKey;
    }

    // ---------- 签名请求 ----------
    private function headers($body)
    {
        $ts = (string) round(microtime(true) * 1000);
        $nonce = bin2hex(random_bytes(16));
        $msg = $this->appId . "\n" . $ts . "\n" . $nonce . "\n" . $body;
        return [
            'Content-Type: application/json',
            'X-Kzy-AppId: ' . $this->appId,
            'X-Kzy-Timestamp: ' . $ts,
            'X-Kzy-Nonce: ' . $nonce,
            'X-Kzy-Sign: ' . hash_hmac('sha256', $msg, $this->appSecret),
        ];
    }

    private function call($method, $path, $payload = null, $raw = false, $saveTo = null)
    {
        $body = $payload === null ? '' : json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $ch = curl_init(KZY_BASE . $path);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $this->headers($body),
            CURLOPT_SSL_VERIFYPEER => true,
        ]);
        if ($payload !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        }
        if ($saveTo !== null) {
            $fp = fopen($saveTo, 'wb');
            curl_setopt($ch, CURLOPT_FILE, $fp);
        }
        $resp = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (isset($fp)) {
            fclose($fp);
        }
        if ($resp === false) {
            $err = curl_error($ch);
            curl_close($ch);
            throw new RuntimeException('网络请求失败：' . $err);
        }
        curl_close($ch);
        if ($saveTo !== null) {
            if ($code != 200) {
                $txt = @file_get_contents($saveTo);
                @unlink($saveTo);
                throw new RuntimeException('下载失败（HTTP ' . $code . '）：' . mb_substr((string) $txt, 0, 200));
            }
            return true;
        }
        $j = json_decode($resp, true);
        if (!is_array($j)) {
            throw new RuntimeException('返回不是 JSON（HTTP ' . $code . '）：' . mb_substr($resp, 0, 200));
        }
        if (($j['code'] ?? -1) != 0) {
            throw new RuntimeException('接口报错：' . ($j['msg'] ?? ('code=' . ($j['code'] ?? '?'))));
        }
        return $j['data'] ?? [];
    }

    // ---------- 接口 ----------
    public function status()
    {
        return $this->call('GET', '/open/v1/upgrade/status?siteKey=' . urlencode($this->siteKey));
    }

    public function apply($releaseId)
    {
        return $this->call('POST', '/open/v1/upgrade/apply', [
            'siteKey' => $this->siteKey, 'releaseId' => (int) $releaseId,
        ]);
    }

    public function task()
    {
        return $this->call('GET', '/open/v1/upgrade/task?siteKey=' . urlencode($this->siteKey));
    }

    private function report($taskId, $ok, $toVersion, $message)
    {
        return $this->call('POST', '/open/v1/upgrade/report', [
            'siteKey' => $this->siteKey,
            'taskId' => (int) $taskId,
            'ok' => $ok,
            'toVersion' => $toVersion,
            'message' => mb_substr((string) $message, 0, 800),
            'updaterVersion' => '1.0.0',
        ]);
    }

    // ---------- 升级 ----------
    public function run($verbose = true)
    {
        $log = [];
        $t = $this->task();
        if (!$t) {
            throw new RuntimeException('还没有升级任务，先执行 apply <版本号> 申请');
        }
        if ((int) $t['status'] === 3) {
            return ['ok' => true, 'message' => '当前任务已完成：' . $t['version']];
        }
        if ((int) $t['status'] !== 1) {
            throw new RuntimeException('任务状态是「' . ($t['statusLabel'] ?? $t['status']) . '」，需运维批准后才能执行');
        }
        $ver = $t['version'];
        $taskId = $t['id'];
        @mkdir($this->tmp, 0755, true);
        @mkdir($this->backup, 0755, true);
        $zip = $this->tmp . '/pkg.zip';

        try {
            $this->say($log, $verbose, '下载升级包 v' . $ver);
            $this->call('GET', '/open/v1/upgrade/download?siteKey=' . urlencode($this->siteKey) . '&taskId=' . $taskId,
                null, false, $zip);
            $sha = hash_file('sha256', $zip);
            $this->say($log, $verbose, '校验 SHA256 ' . substr($sha, 0, 16) . '…');

            $stage = $this->tmp . '/stage';
            $this->rmdir($stage);
            @mkdir($stage, 0755, true);
            $zp = new ZipArchive();
            if ($zp->open($zip) !== true) {
                throw new RuntimeException('升级包无法解压');
            }
            $zp->extractTo($stage);
            $zp->close();
            $base = $this->detectBase($stage);

            $files = $this->listFiles($base);
            if (!$files) {
                throw new RuntimeException('升级包是空的');
            }
            $bk = $this->backup . '/' . $ver . '_' . date('YmdHis');
            $count = 0;
            foreach ($files as $rel) {
                if ($this->excluded($rel)) {
                    continue;
                }
                $src = $base . '/' . $rel;
                $dst = $this->root . '/' . $rel;
                if (is_file($dst)) {
                    @mkdir(dirname($bk . '/' . $rel), 0755, true);
                    copy($dst, $bk . '/' . $rel);
                }
                @mkdir(dirname($dst), 0755, true);
                if (!copy($src, $dst)) {
                    throw new RuntimeException('写入失败：' . $rel);
                }
                $count++;
            }
            $this->say($log, $verbose, '已覆盖 ' . $count . ' 个文件，备份在 .kzy_backup/' . basename($bk));

            if (KZY_HOOK_AFTER !== '') {
                $out = [];
                exec(KZY_HOOK_AFTER . ' 2>&1', $out, $rc);
                $this->say($log, $verbose, '执行升级后命令 rc=' . $rc . ' ' . implode(' ', array_slice($out, -3)));
            }
            $this->rmdir($this->tmp);
            $msg = '覆盖 ' . $count . ' 个文件，备份 .kzy_backup/' . basename($bk);
            $this->report($taskId, true, $ver, $msg);
            return ['ok' => true, 'message' => '升级到 v' . $ver . ' 成功，' . $msg, 'log' => $log];
        } catch (Throwable $e) {
            $this->rmdir($this->tmp);
            try {
                $this->report($taskId, false, null, $e->getMessage());
            } catch (Throwable $ignore) {
            }
            return ['ok' => false, 'message' => '升级失败：' . $e->getMessage(), 'log' => $log];
        }
    }

    public function rollback($verbose = true)
    {
        $dirs = glob($this->backup . '/*', GLOB_ONLYDIR);
        if (!$dirs) {
            throw new RuntimeException('没有可回滚的备份');
        }
        sort($dirs);
        $last = end($dirs);
        $n = 0;
        foreach ($this->listFiles($last) as $rel) {
            @mkdir(dirname($this->root . '/' . $rel), 0755, true);
            if (copy($last . '/' . $rel, $this->root . '/' . $rel)) {
                $n++;
            }
        }
        if (KZY_HOOK_AFTER !== '') {
            exec(KZY_HOOK_AFTER . ' 2>&1');
        }
        return ['ok' => true, 'message' => '已回滚 ' . $n . ' 个文件（来源 .kzy_backup/' . basename($last) . '）'];
    }

    // ---------- 工具 ----------
    private function excluded($rel)
    {
        foreach (KZY_EXCLUDE as $x) {
            if ($rel === $x || strpos($rel, $x . '/') === 0) {
                return true;
            }
        }
        return false;
    }

    /** 若 zip 里只有一层同名目录（如 www/），自动下钻 */
    private function detectBase($stage)
    {
        $items = array_values(array_diff(scandir($stage), ['.', '..']));
        if (count($items) === 1 && is_dir($stage . '/' . $items[0])) {
            $inner = array_values(array_diff(scandir($stage . '/' . $items[0]), ['.', '..']));
            if ($inner && !in_array('index.php', $inner) && !in_array('index.html', $inner)) {
                return $stage . '/' . $items[0];
            }
        }
        return $stage;
    }

    private function listFiles($base)
    {
        $out = [];
        $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS));
        foreach ($it as $f) {
            if ($f->isFile()) {
                $out[] = str_replace('\\', '/', substr($f->getPathname(), strlen($base) + 1));
            }
        }
        return $out;
    }

    private function rmdir($dir)
    {
        if (!is_dir($dir)) {
            return;
        }
        $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST);
        foreach ($it as $f) {
            $f->isDir() ? @rmdir($f->getPathname()) : @unlink($f->getPathname());
        }
        @rmdir($dir);
    }

    private function say(&$log, $verbose, $line)
    {
        $log[] = $line;
        if ($verbose) {
            echo '  ' . $line . PHP_EOL;
        }
    }
}

// ====================== 命令行 ======================
if (PHP_SAPI === 'cli') {
    $cmd = $argv[1] ?? 'status';
    $u = new KzyUpgrader();
    try {
        if ($cmd === 'license') {
            $lic = $argv[2] ?? KZY_LICENSE;
            if ($lic === '') {
                exit("用法：php kzy-upgrade.php license LIC20261127018 [站点域名]\n"
                    . "授权号在运维中心「授权管理」里，需要运维先点过「开通升级」。\n");
            }
            $d = $u->provision($lic, $argv[3] ?? null);
            echo '✅ 已接入运维中心' . PHP_EOL;
            echo '  站点    ：' . ($d['siteName'] ?? '') . PHP_EOL;
            echo '  产品线  ：' . ($d['productKey'] ?? '') . PHP_EOL;
            echo '  授权到期：' . ($d['expireDate'] ?? '') . PHP_EOL;
            echo '  siteKey ：' . ($d['siteKey'] ?? '') . PHP_EOL;
            echo '  凭据已写入 .kzy-upgrade.state.json（权限 600，不会覆盖你的站点文件）' . PHP_EOL;
            echo '  下一步  ：php kzy-upgrade.php status' . PHP_EOL;
            exit(0);
        }
        $u->ensureCredentialsPublic();
        if ($cmd === 'status') {
            $d = $u->status();
            echo '站点：' . ($d['site']['siteName'] ?? '') . '  当前版本：' . (($d['site']['currentVersion'] ?? '') ?: '未登记') . PHP_EOL;
            echo '可用版本：' . PHP_EOL;
            foreach ($d['releases'] as $r) {
                echo '  ' . $r['version'] . '  ' . round($r['size'] / 1024) . 'KB  '
                    . ($r['installed'] ? '[已安装]' : '') . '  ' . str_replace("\n", ' ', (string) $r['notes']) . PHP_EOL;
            }
            if (!empty($d['task'])) {
                echo '当前任务：' . $d['task']['version'] . ' → ' . $d['task']['statusLabel'] . PHP_EOL;
            }
        } elseif ($cmd === 'apply') {
            $d = $u->status();
            $ver = $argv[2] ?? '';
            $hit = null;
            foreach ($d['releases'] as $r) {
                if ($ver === '' || $r['version'] === $ver) {
                    $hit = $r;
                    if ($ver !== '') {
                        break;
                    }
                }
            }
            if (!$hit) {
                exit('没有找到版本 ' . $ver . PHP_EOL);
            }
            $t = $u->apply($hit['releaseId']);
            echo '已申请升级到 v' . $hit['version'] . '，任务 #' . $t['id'] . '，状态：' . $t['statusLabel'] . PHP_EOL;
            echo '等运维在后台批准后，再执行 php kzy-upgrade.php run' . PHP_EOL;
        } elseif ($cmd === 'run') {
            $r = $u->run(true);
            echo $r['message'] . PHP_EOL;
            exit($r['ok'] ? 0 : 1);
        } elseif ($cmd === 'rollback') {
            $r = $u->rollback(true);
            echo $r['message'] . PHP_EOL;
        } else {
            echo "用法：" . PHP_EOL;
            echo "  php kzy-upgrade.php license LIC2026xxxxxx [站点域名]   首次接入（只填授权号）" . PHP_EOL;
            echo "  php kzy-upgrade.php status                            看当前版本和可用版本" . PHP_EOL;
            echo "  php kzy-upgrade.php apply 1.2.3                       申请升级" . PHP_EOL;
            echo "  php kzy-upgrade.php run                                批准后执行" . PHP_EOL;
            echo "  php kzy-upgrade.php rollback                           回滚" . PHP_EOL;
        }
    } catch (Throwable $e) {
        echo '错误：' . $e->getMessage() . PHP_EOL;
        exit(1);
    }
    exit(0);
}

// ====================== 网页 ======================
if (($_GET['token'] ?? '') !== KZY_WEB_TOKEN) {
    http_response_code(403);
    exit('口令错误');
}
$u = new KzyUpgrader();
$msg = '';
$ok = true;
$action = $_POST['action'] ?? '';
try { $u->ensureCredentialsPublic(); } catch (Throwable $e) { $msg = $e->getMessage(); $ok = false; }
try {
    if ($action === 'apply') {
        $t = $u->apply($_POST['releaseId']);
        $msg = '已申请升级到 v' . $t['version'] . '，等运维批准后点「立即升级」';
    } elseif ($action === 'run') {
        $r = $u->run(false);
        $msg = $r['message'];
        $ok = $r['ok'];
    } elseif ($action === 'rollback') {
        $r = $u->rollback(false);
        $msg = $r['message'];
    }
} catch (Throwable $e) {
    $msg = $e->getMessage();
    $ok = false;
}
$d = null;
try {
    $d = $u->status();
} catch (Throwable $e) {
    $msg = $msg ?: ('连不上运维中心：' . $e->getMessage());
    $ok = false;
}
$cur = $d['site']['currentVersion'] ?? '';
$task = $d['task'] ?? null;
?>
<!DOCTYPE html>
<html lang="zh-CN"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>系统升级 · 康之源运维</title>
<style>
body{margin:0;background:#f4f6fa;font:14px/1.6 -apple-system,"Microsoft YaHei",sans-serif;color:#0f2038}
.wrap{max-width:760px;margin:28px auto;padding:0 16px}
.card{background:#fff;border:1px solid #e6eaf2;border-radius:12px;padding:18px 20px;margin-bottom:14px}
h2{font-size:17px;margin:0 0 12px;padding-left:9px;border-left:3px solid #2563eb}
.tag{display:inline-block;padding:1px 8px;border-radius:10px;font-size:12px}
.on{background:#ecfdf5;color:#047857}.off{background:#f3f4f6;color:#6b7280}
.rel{display:flex;align-items:center;gap:12px;padding:10px 0;border-top:1px dashed #eef1f6}
.rel:first-of-type{border-top:0}
.rel .v{font-weight:600;font-size:15px}
.rel .n{color:#6b7280;font-size:12.5px;flex:1;white-space:pre-wrap}
button{background:#2563eb;color:#fff;border:0;border-radius:8px;padding:7px 14px;font-size:13px;cursor:pointer}
button.ghost{background:#fff;color:#b45309;border:1px solid #f0d5a8}
.msg{padding:10px 14px;border-radius:9px;margin-bottom:14px;font-size:13.5px}
.msg.ok{background:#ecfdf5;color:#047857;border:1px solid #c7f0dd}
.msg.err{background:#fef2f2;color:#b91c1c;border:1px solid #fecaca}
</style></head><body><div class="wrap">
<?php if ($msg): ?><div class="msg <?= $ok ? 'ok' : 'err' ?>"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
<div class="card">
  <h2>当前状态</h2>
  <div>站点：<b><?= htmlspecialchars($d['site']['siteName'] ?? '') ?></b></div>
  <div>当前版本：<b><?= htmlspecialchars($cur ?: '未登记') ?></b></div>
  <?php if ($task): ?>
  <div>升级任务：v<?= htmlspecialchars($task['version']) ?>
    <span class="tag <?= $task['status'] == 3 ? 'on' : 'off' ?>"><?= htmlspecialchars($task['statusLabel']) ?></span></div>
  <?php endif; ?>
</div>
<div class="card">
  <h2>可用版本</h2>
  <?php if (empty($d['releases'])): ?><div style="color:#6b7280">暂无发布版本</div><?php endif; ?>
  <?php foreach (($d['releases'] ?? []) as $r): ?>
  <div class="rel">
    <div class="v">v<?= htmlspecialchars($r['version']) ?></div>
    <div class="n"><?= htmlspecialchars((string) $r['notes']) ?></div>
    <?php if ($r['installed']): ?><span class="tag on">已安装</span>
    <?php elseif ($task && $task['releaseId'] == $r['releaseId'] && $task['status'] == 1): ?>
      <form method="post"><input type="hidden" name="action" value="run"><button>立即升级</button></form>
    <?php else: ?>
      <form method="post"><input type="hidden" name="action" value="apply">
        <input type="hidden" name="releaseId" value="<?= (int) $r['releaseId'] ?>">
        <button>申请升级</button></form>
    <?php endif; ?>
  </div>
  <?php endforeach; ?>
</div>
<div class="card">
  <h2>回滚</h2>
  <div style="color:#6b7280;font-size:12.5px;margin-bottom:10px">升级前会自动备份被覆盖的文件，出问题可还原到上一次升级前。</div>
  <form method="post" onsubmit="return confirm('确定回滚到上一次升级前的版本？')">
    <input type="hidden" name="action" value="rollback"><button class="ghost">回滚</button></form>
</div>
</div></body></html>
