<?php

namespace App\Services\TG\Hook\Mod;
use App\Models\Article as ModelArticle;

class Git extends Base {
    
    public function urlList()
    {
        $aArticleList = ModelArticle::orderBy('user_name')->get()->toArray();
        
        $sMsg = '';
        foreach ($aArticleList as $v) {
            $sMsg .= "\n\n";
            $sMsg .= "https://github.com/".$v['user_name']."/".$v['project_name'];
        }
        
        return $sMsg;
        
    }
    
    public function lastTime($aParam)
    {
        $iId = $aParam['aArg'][1];
        
        $aArticle = ModelArticle::find($iId);
        
        $sProjectPath = env("BASE_DIR") . "github/" . $aArticle->user_name . "-" . $aArticle->project_name;
        
        // 进入指定目录
        if (!chdir($sProjectPath)) {
            throw new \Exception("无法进入目录" . $sProjectPath);
        }

        // 获取远程更新
        $this->runCommand('git fetch origin');

        // 获取最后提交的时间
        $lastCommitTime = $this->runCommand('git log origin/main -1 --format=%cd');
        $lastCommitTime = \DateTime::createFromFormat('D M d H:i:s Y O', $lastCommitTime[0]);
        $lastCommitTime = json_encode($lastCommitTime->format('Y-m-d H:i:s'));

        // 检查是否获取到时间
        if (empty($lastCommitTime)) {
            throw new \Exception("无法获取最后提交时间，可能是分支不存在或没有提交。");
        }

        return $lastCommitTime;
        
    }
    
    // 没用
    public function addSshHostGithub()
    {

        // 定义要添加的主机
        $host = 'github.com';

        // 执行 ssh-keyscan 命令
        $key = shell_exec("ssh-keyscan -t ed25519 $host");

        // 检查是否成功获取到公钥
        if ($key) {
            // 获取 known_hosts 文件的路径
            $knownHostsFile = '/root/.ssh/known_hosts';

            // 检查 known_hosts 文件中是否已经存在该主机的公钥
            if (strpos(file_get_contents($knownHostsFile), $host) === false) {
                // 将公钥写入 known_hosts 文件
                file_put_contents($knownHostsFile, $key, FILE_APPEND);
                $sMsg = "公钥已成功添加到 $knownHostsFile\n";
            } else {
                $sMsg = "公钥已存在于 $knownHostsFile\n";
            }
        } else {
            $sMsg = "无法获取 $host 的公钥\n";
        }
        
        return $sMsg;
//        $this->oTGHttp->sendToTG($sMsg);
        
//        $this->oHttp::response(200, 'ok');
        
    }
    
    // /Git#PullR 3
    public function aullR($aParam)
    {
        
        $iId = $aParam['aArg'][1];
        
        $aArticle = ModelArticle::find($iId);
        
        $sProjectPath = env("BASE_DIR")."github/".$aArticle->user_name."-".$aArticle->project_name;
        
        // 进入指定目录
        if (!chdir($sProjectPath)) {
            throw new \Exception("无法进入目录".$sProjectPath);
        }

        // 获取远程更新
        $this->runCommand('git fetch origin');

        // 硬重置到远程主分支
        $this->runCommand('git reset --hard origin/main');
        
        return "操作完成：已重置到远程主分支";
//        $this->oTGHttp->sendToTG("操作完成：已重置到远程主分支");
        
//        $this->oHttp::response(200, 'ok');
        
    }
    
    private function runCommand($command) {
        $output = [];
        $returnVar = 0;
        exec($command, $output, $returnVar);
        
        if ($returnVar !== 0) {
            $jsonOutput = json_encode($output, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            $errorMessage = "命令失败: $command\n" . $jsonOutput . "\n";
            
            throw new \Exception($errorMessage);
        } else {
            return $output;
        }
        
    }
    
}
