From 2956d14d9434542c709cad36002a8a0630c21b33 Mon Sep 17 00:00:00 2001 From: PTah Date: Tue, 16 Jun 2026 11:36:51 +1000 Subject: [PATCH] chore(docs): GitHub repo URLs, remove .cursor from git, mirror scripts Co-authored-by: Cursor --- .cursor/rules/01-context-control.md | 32 --------- .cursor/rules/agent-monitors-version-bump.mdc | 38 ----------- .cursor/rules/no-cursor-in-repositories.mdc | 30 --------- .cursor/rules/powershell-spec.md | 18 ----- .cursor/rules/python-spec.md | 14 ---- .cursor/rules/version-bump-rdp.mdc | 31 --------- .cursor/rules/version-bump-ssh.mdc | 28 -------- .gitignore | 3 +- README.md | 2 +- docs/auto-update.ru.md | 4 +- scripts/Push-Mirror.ps1 | 41 ++++++++++++ scripts/Rewrite-GitHostUrls.ps1 | 57 ++++++++++++++++ scripts/push-mirror.sh | 43 ++++++++++++ scripts/rewrite-git-host-urls.sh | 67 +++++++++++++++++++ ssh-monitor.conf.example | 2 +- update_ssh_monitor.sh | 4 +- 16 files changed, 216 insertions(+), 198 deletions(-) delete mode 100644 .cursor/rules/01-context-control.md delete mode 100644 .cursor/rules/agent-monitors-version-bump.mdc delete mode 100644 .cursor/rules/no-cursor-in-repositories.mdc delete mode 100644 .cursor/rules/powershell-spec.md delete mode 100644 .cursor/rules/python-spec.md delete mode 100644 .cursor/rules/version-bump-rdp.mdc delete mode 100644 .cursor/rules/version-bump-ssh.mdc create mode 100644 scripts/Push-Mirror.ps1 create mode 100644 scripts/Rewrite-GitHostUrls.ps1 create mode 100644 scripts/push-mirror.sh create mode 100644 scripts/rewrite-git-host-urls.sh diff --git a/.cursor/rules/01-context-control.md b/.cursor/rules/01-context-control.md deleted file mode 100644 index a5754f1..0000000 --- a/.cursor/rules/01-context-control.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -description: Global token-saving, cost control, and context management rules -globs: * ---- - -# Global Optimization & Cost Control - -## ?? Answers --Always answer briefly and only to the point, otherwise only if it is stated in the question or when it is not possible to answer briefly. - -## ?? Context & Local Data -- **Strict file targeting:** Work ONLY with files explicitly provided via `@` or open in the active editor tab. Do not use global codebase search unless requested. -- **Local assets only:** Always work with local copies of repositories and dependencies. Never request external web resources or re-download packages without a explicit build error. -- **Size Limit:** Do not load files larger than 500 lines into the context unless strictly necessary. - -## ?? Git & Commits Management -- **Automatic commits are strictly FORBIDDEN.** Never execute `git commit` or `git push` without an explicit user command. -- Only suggest a commit after phrases like: " ", " ", "Push". -- Before committing: display `git diff --stat` and wait for explicit user confirmation. -- Use Conventional Commits format (`feat:`, `fix:`, `refactor:`, `docs:`). - -## ?? Output Format & Brevity -- **Strictly no fluff:** Omit greetings, apologies, and closing pleasantries. -- **Diff-style only:** Output only modified code fragments, never duplicate unchanged logic or whole files. -- **Extreme brevity:** Explanations must be 1-3 sentences max. Use documentation links instead of long texts. -- If a task doesn't require code, respond strictly with text. If in doubt, ask ONE precise clarifying question. - -## ?? Model Routing Reminder -- Simple questions, explanations, docs ? Use lightweight models (e.g., `gpt-4o-mini`, `claude-3-haiku`). -- Complex code generation, refactoring, and debugging ? Use advanced models (e.g., `claude-3.5-sonnet`). -- Do not switch models without an explicit reason. - diff --git a/.cursor/rules/agent-monitors-version-bump.mdc b/.cursor/rules/agent-monitors-version-bump.mdc deleted file mode 100644 index c5a6ae3..0000000 --- a/.cursor/rules/agent-monitors-version-bump.mdc +++ /dev/null @@ -1,38 +0,0 @@ ---- -description: При правках агентских скриптов (RDP/SSH) всегда bump версии — иначе ПК не обновятся -alwaysApply: true ---- - -# Версии агентов: обязательный bump - -Workspace **security-monitors** (RDP + SSH + SAC). Любая **существенная правка агентских скриптов** без bump версии **не доедет до компьютеров**. - -## RDP-login-monitor - -| Файл | Поле | -|------|------| -| `Login_Monitor.ps1` | `$ScriptVersion` | -| `version.txt` | та же строка | - -Триггер деплоя на Windows: **`Deploy-LoginMonitor.ps1`** сравнивает `version.txt` на шаре с `C:\ProgramData\RDP-login-monitor\deployed_version.txt`. - -## ssh-monitor - -| Файл | Поле | -|------|------| -| `ssh-monitor` | `SSH_MONITOR_VERSION` | -| `version.txt` | та же строка | - -Обновление на Linux: **`update_ssh_monitor.sh`** (sha256 + перезапуск сервиса). - -## Правило для агента - -При изменении `Login_Monitor.ps1`, `Deploy-LoginMonitor.ps1`, `Sac-Client.ps1`, `ssh-monitor`, `sac-client.sh`, `update_ssh_monitor.sh`: - -1. Поднять **patch** версии (`2.0.6-SAC` → `2.0.7-SAC`) в **обоих** местах репозитория -2. Включить bump в **тот же коммит**, что и правку (или сразу следом `chore: bump release to …`) -3. Напомнить: опубликовать RDP на NETLOGON / на SSH-хостах выполнить update - -## SAC (backend) - -Версия UI/API — `backend/app/version.py` (`APP_VERSION`). Bump при релизе SAC на сервер; на автообновление **агентов на ПК** не влияет. diff --git a/.cursor/rules/no-cursor-in-repositories.mdc b/.cursor/rules/no-cursor-in-repositories.mdc deleted file mode 100644 index c714edc..0000000 --- a/.cursor/rules/no-cursor-in-repositories.mdc +++ /dev/null @@ -1,30 +0,0 @@ ---- -description: Запрет упоминаний Cursor IDE/Agent в git-репозиториях (файлы и коммиты) -alwaysApply: true ---- - -# Не оставлять следов Cursor в репозиториях - -В **коммитах и файлах**, которые попадают в git (включая публичный GitHub), **запрещено** добавлять что-либо, связанное с Cursor как инструментом разработки. - -## Запрещено - -- Упоминания **Cursor**, **Cursor IDE**, **Cursor Agent**, **cursoragent**, **cursor.com**, **cursor.sh** в README, docs, комментариях, конфигах. -- Trailers в сообщениях коммитов: `Co-authored-by: Cursor …`, `Made-with: Cursor`, email `cursoragent@cursor.com`. -- Каталог **`.cursor/`**, файлы только для IDE (**`AGENTS.md`**, **`CURSOR.md`**) — **не коммитить** в публичные репозитории (должны быть в `.gitignore`, если репо public). -- Ссылки на Cursor в runbook, deploy-доках, issue templates. - -## Разрешено (не путать с IDE) - -- CSS: **`cursor: pointer`** (и аналоги). -- Предметный код: **poll cursor**, **CurrentCursor**, **Update-MonitorPollCursor**, **Console.CursorLeft**, **DB cursor** (sqlite/psycopg2), **MOEX `analytics.cursor`** и т.п. - -## Git / GitHub - -- **Author и committer** — только владелец проекта (**Andrey Lutsenko**, email, привязанный к GitHub), **без** co-author Cursor. -- Перед push в public remote: нет `cursoragent`, `Co-authored-by: Cursor` в истории и дереве (`git log --format=fuller`, поиск по репо). - -## При работе агента - -- Не добавлять «Powered by Cursor», бейджи, секции про Cursor в документацию продукта. -- Правила Cursor (`.cursor/rules/`) — локально или только в **приватном** remote; в публичный GitHub не попадают. diff --git a/.cursor/rules/powershell-spec.md b/.cursor/rules/powershell-spec.md deleted file mode 100644 index f85d9d6..0000000 --- a/.cursor/rules/powershell-spec.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -description: High-density PowerShell script generation rules for minimal token usage -globs: "*.ps1, *.psm1" ---- - -# PowerShell Token Optimization - -- **Use Short Aliases:** Use short aliases instead of full cmdlet names to drastically cut output tokens: - - Use `gc` instead of `Get-Content` - - Use `gci` instead of `Get-ChildItem` - - Use `%` instead of `ForEach-Object` - - Use `?` instead of `Where-Object` - - Use `measure` instead of `Measure-Object` -- **Pipeline Over Loops:** Prefer pipeline chains (`gci | % { ... }`) over multi-line `foreach ($item in $items) { ... }` blocks. -- **No Help/Comments:** Do not generate `.SYNOPSIS`, `.DESCRIPTION`, or comment-based help at the top of scripts. -- **Omit Parameter Names:** Drop explicit parameter names where positional arguments are clear (e.g., use `gc file.txt` instead of `Get-Content -Path file.txt`). -- **Silent Execution:** Do not add verbose logging, `Write-Host`, or `Write-Output` unless explicitly asked to create UI/logs. -- **Preserve CLI Arguments:** Do not duplicate full multi-line `yt-dlp` command-line arguments, format strings, or output templates if they are not the subject of the modifications. Use placeholders or variable references. diff --git a/.cursor/rules/python-spec.md b/.cursor/rules/python-spec.md deleted file mode 100644 index fb0ad8e..0000000 --- a/.cursor/rules/python-spec.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -description: Ultra-dense Python code generation rules to save output tokens -globs: "*.py" ---- - -# Python Token Optimization - -- **Use Syntactic Sugar:** Prioritize list comprehensions, dict comprehensions, and ternary operators (`x if condition else y`) to keep code on a single line. -- **Built-in Libraries First:** Use standard libraries (`pathlib`, `json`, `subprocess`, `asyncio`) instead of introducing heavy external dependencies unless already in `requirements.txt`. -- **Type Hinting:** Do NOT add type hints (`def func(x: int) -> str:`) unless the existing file strictly uses them. Type hints consume significant tokens. -- **No Format Duplication:** When modifying scripts (like video downloaders), provide only the modified function or class method. Never output the `if __name__ == "__main__":` block or argument parsing logic if they haven't changed. -- **No Docstrings:** Strictly forbid writing `"""docstrings"""` or `# comments` explaining the logic. -- **Preserve yt-dlp Options:** Never rewrite, duplicate, or expand the `ydl_opts` configuration dictionary or custom extraction options. If changes are unrelated to download options, use a placeholder comment like `# ... existing ydl_opts ...` instead of outputting the full dictionary block. - diff --git a/.cursor/rules/version-bump-rdp.mdc b/.cursor/rules/version-bump-rdp.mdc deleted file mode 100644 index ead828e..0000000 --- a/.cursor/rules/version-bump-rdp.mdc +++ /dev/null @@ -1,31 +0,0 @@ ---- -description: При правке скриптов RDP-монитора обязательно поднимать version.txt и $ScriptVersion -globs: Login_Monitor.ps1,Deploy-LoginMonitor.ps1,Sac-Client.ps1,Exchange-MailSecurity.ps1,Watchdog_RDP_Monitor.ps1,version.txt -alwaysApply: false ---- - -# Bump версии RDP-login-monitor - -Без новой версии **`Deploy-LoginMonitor.ps1` на ПК не подхватит обновление** (сравнение `version.txt` на шаре с `deployed_version.txt`). - -## Что менять в одном коммите с правкой - -1. **`Login_Monitor.ps1`** — `$ScriptVersion` (например `2.0.7-SAC`) -2. **`version.txt`** — **та же строка**, одна строка без лишнего текста - -Строки должны **совпадать** (включая суффикс `-SAC`). - -## Как поднимать - -- Обычная правка монитора / deploy / SAC-клиента → **patch**: `2.0.6-SAC` → `2.0.7-SAC` -- Крупный релиз → по смыслу **minor** (`2.0.x` → `2.1.0-SAC`) - -## Другие скрипты с собственной версией - -- **`Exchange-MailSecurity.ps1`** — отдельный `$ScriptVersion`; bump только если меняли этот пакет -- После bump опубликовать на шару NETLOGON (`update-rdp-monitor.ps1` / pull на сервере публикации) - -## Чеклист перед push - -- [ ] `$ScriptVersion` и `version.txt` совпадают -- [ ] Версия на шаре будет **новее** локальной `deployed_version.txt` на клиентах diff --git a/.cursor/rules/version-bump-ssh.mdc b/.cursor/rules/version-bump-ssh.mdc deleted file mode 100644 index f532984..0000000 --- a/.cursor/rules/version-bump-ssh.mdc +++ /dev/null @@ -1,28 +0,0 @@ ---- -description: При правке ssh-monitor обязательно поднимать version.txt и SSH_MONITOR_VERSION -globs: ssh-monitor,sac-client.sh,update_ssh_monitor.sh,version.txt -alwaysApply: false ---- - -# Bump версии ssh-monitor - -Без bump **`update_ssh_monitor.sh` не скопирует новый скрипт** на хост (сравнение sha256; версия нужна для отчётов, SAC и диагностики). - -## Что менять в одном коммите с правкой - -1. **`ssh-monitor`** — `SSH_MONITOR_VERSION="X.Y.Z-SAC"` (первая строка блока версии) -2. **`version.txt`** — **та же строка** - -Строки должны **совпадать**. - -## Как поднимать - -- Обычная правка → **patch**: `2.0.0-SAC` → `2.0.1-SAC` -- Крупный релиз → **minor** по смыслу - -`sac-client.sh` отдельный номер **не** задаёт — берёт `SSH_MONITOR_VERSION` из установленного `ssh-monitor`. - -## Чеклист перед push - -- [ ] `SSH_MONITOR_VERSION` и `version.txt` совпадают -- [ ] На хостах: `git pull` и запуск `update_ssh_monitor.sh` (или `--deploy`) diff --git a/.gitignore b/.gitignore index 6197cf9..f70c3a2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,8 @@ .DS_Store CalculatorApp/ +.cursor/ -# .env — не коммитить; ssh-monitor.conf с секретами допустим только на git.kalinamall.ru +# .env — не коммитить; ssh-monitor.conf с секретами допустим только в закрытом зеркале (не в публичном GitHub) .env .env.* # Артефакты локальной сборки (релизные архивы грузятся в GitHub Releases, в git не коммитим) diff --git a/README.md b/README.md index 539d4a2..c641186 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Bash-скрипт мониторинга **SSH**, **SUDO** и событий **` ## Конфигурация -> **git.kalinamall.ru:** в этом закрытом репозитории допустимо хранить **`ssh-monitor.conf`** с боевыми токенами и паролями (файл не в `.gitignore`). В публичном [GitHub](https://github.com/PTah/ssh-monitor) такой файл игнорируется — используйте только `ssh-monitor.conf.example`. +> **Закрытый инстанс Gitea:** в доверенном закрытом репозитории допустимо хранить **`ssh-monitor.conf`** с боевыми токенами (файл не в `.gitignore`). В публичном [GitHub](https://github.com/PTah/ssh-monitor) такой файл игнорируется — используйте только `ssh-monitor.conf.example`. Скрипт читает параметры из `/etc/ssh-monitor.conf` в формате `KEY="value"`. diff --git a/docs/auto-update.ru.md b/docs/auto-update.ru.md index 0abd2a1..28c852f 100644 --- a/docs/auto-update.ru.md +++ b/docs/auto-update.ru.md @@ -41,7 +41,7 @@ flowchart LR | Переменная | По умолчанию | Назначение | |------------|--------------|------------| | `UPDATE_DIR` | `/opt/scripts/update` | Каталог для git-клона | -| `REPO_URL` | `https://git.kalinamall.ru/PapaTramp/ssh-monitor.git` | URL закрытого репозитория (на GitHub в репо — placeholder) | +| `REPO_URL` | `https://github.com/PTah/ssh-monitor.git` | URL репозитория (на закрытом зеркале — URL своего Gitea) | | `LOCAL_SCRIPT_PATH` | `/usr/local/bin/ssh-monitor` | Куда копировать бинарник | | `LOG_FILE` | `/var/log/update_script.log` | Лог обновлений | | `DEBUG` | `0` | `1` — подробный DEBUG в лог | @@ -169,4 +169,4 @@ sudo /opt/scripts/update_ssh_monitor.sh - Обновляется **только** файл **`ssh-monitor`**, не конфиг и не watchdog. - При недоступном git **`git pull`** пишет предупреждение и продолжает с локальной копией. -- На **git.kalinamall.ru** в `update_ssh_monitor.sh` уже задан внутренний **`REPO_URL`**; на GitHub остаётся placeholder для форка. +- На **закрытом зеркале** в `update_ssh_monitor.sh` задайте **`REPO_URL`** своего Gitea; в публичном GitHub по умолчанию — `github.com/PTah/ssh-monitor`. diff --git a/scripts/Push-Mirror.ps1 b/scripts/Push-Mirror.ps1 new file mode 100644 index 0000000..4602a60 --- /dev/null +++ b/scripts/Push-Mirror.ps1 @@ -0,0 +1,41 @@ +# Push main to a mirror remote with host-specific doc URLs, without leaving URL churn on main. +# Usage: .\scripts\Push-Mirror.ps1 github|kalinamall|papatramp +param( + [Parameter(Mandatory = $true)] + [ValidateSet('github', 'kalinamall', 'papatramp')] + [string]$Target +) + +$ErrorActionPreference = 'Stop' +$Root = Split-Path -Parent $PSScriptRoot +Set-Location $Root + +$remote = switch ($Target) { + 'github' { 'github' } + 'kalinamall' { 'kalinamall' } + 'papatramp' { 'papatramp' } +} + +git remote get-url $remote 2>$null | Out-Null +if ($LASTEXITCODE -ne 0) { + throw "remote not configured: $remote" +} + +if ((git status --porcelain)) { + throw 'working tree not clean; commit or stash first' +} + +$before = (git rev-parse HEAD).Trim() +& "$PSScriptRoot\Rewrite-GitHostUrls.ps1" -Target $Target + +if (-not (git status --porcelain)) { + Write-Output "no URL changes for $Target; pushing as-is" + git push $remote main + exit 0 +} + +git add -A +git commit -m "chore(docs): sync repository URLs for ${Target} mirror" +git push $remote main +git reset --hard $before +Write-Output "pushed $remote with ${Target} URLs; local main reset to $before" diff --git a/scripts/Rewrite-GitHostUrls.ps1 b/scripts/Rewrite-GitHostUrls.ps1 new file mode 100644 index 0000000..87a40f5 --- /dev/null +++ b/scripts/Rewrite-GitHostUrls.ps1 @@ -0,0 +1,57 @@ +# Rewrite cross-repo URLs in tracked docs/config for the target Git host. +# Usage: .\scripts\Rewrite-GitHostUrls.ps1 github|kalinamall|papatramp +param( + [Parameter(Mandatory = $true)] + [ValidateSet('github', 'kalinamall', 'papatramp')] + [string]$Target +) + +$ErrorActionPreference = 'Stop' +$Root = Split-Path -Parent $PSScriptRoot +Set-Location $Root + +switch ($Target) { + 'github' { + $Base = 'https://github.com/PTah' + $BlobSuffix = '/blob/main' + } + 'kalinamall' { + $Base = 'https://git.kalinamall.ru/PapaTramp' + $BlobSuffix = '/src/branch/main' + } + 'papatramp' { + $Base = 'https://git.papatramp.ru/PTah' + $BlobSuffix = '/src/branch/main' + } +} + +$BaseHost = $Base -replace '^https://', '' + +$patterns = @( + @{ From = 'https://github.com/PTah/([^)/''"\s]+)/blob/main/'; To = "$Base/`$1$BlobSuffix/" } + @{ From = 'https://git.kalinamall.ru/PapaTramp/([^)/''"\s]+)/src/branch/main/'; To = "$Base/`$1$BlobSuffix/" } + @{ From = 'https://git.papatramp.ru/PTah/([^)/''"\s]+)/src/branch/main/'; To = "$Base/`$1$BlobSuffix/" } + @{ From = 'https://github.com/PTah/'; To = "$Base/" } + @{ From = 'https://git.kalinamall.ru/PapaTramp/'; To = "$Base/" } + @{ From = 'https://git.papatramp.ru/PTah/'; To = "$Base/" } + @{ From = 'github.com/PTah/'; To = "$BaseHost/" } + @{ From = 'git.kalinamall.ru/PapaTramp/'; To = "$BaseHost/" } + @{ From = 'git.papatramp.ru/PTah/'; To = "$BaseHost/" } +) + +$extensions = @('*.md', '*.json', '*.service', '*.example', '*.sh', '*.ps1', '*.yml', '*.yaml') +$files = git ls-files $extensions 2>$null | Where-Object { $_ -and (Test-Path $_) } + +foreach ($file in $files) { + $content = [System.IO.File]::ReadAllText((Join-Path $Root $file)) + $updated = $content + foreach ($p in $patterns) { + $updated = [regex]::Replace($updated, $p.From, $p.To) + } + if ($updated -ne $content) { + [System.IO.File]::WriteAllText((Join-Path $Root $file), $updated, [System.Text.UTF8Encoding]::new($false)) + Write-Output "updated: $file" + } +} + +Write-Output "Rewrite-GitHostUrls: target=$Target base=$Base" diff --git a/scripts/push-mirror.sh b/scripts/push-mirror.sh new file mode 100644 index 0000000..1a119f6 --- /dev/null +++ b/scripts/push-mirror.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Push main to a mirror remote with host-specific doc URLs, without leaving URL churn on main. +# Usage: push-mirror.sh github|kalinamall|papatramp +set -euo pipefail + +TARGET="${1:?usage: push-mirror.sh github|kalinamall|papatramp}" +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" + +case "$TARGET" in + github) REMOTE=github ;; + kalinamall) REMOTE=kalinamall ;; + papatramp) REMOTE=papatramp ;; + *) + echo "unknown target: $TARGET" >&2 + exit 1 + ;; +esac + +if ! git remote get-url "$REMOTE" >/dev/null 2>&1; then + echo "remote not configured: $REMOTE" >&2 + exit 1 +fi + +if ! git diff --quiet || ! git diff --cached --quiet; then + echo "working tree not clean; commit or stash first" >&2 + exit 1 +fi + +BEFORE="$(git rev-parse HEAD)" +bash "$ROOT/scripts/rewrite-git-host-urls.sh" "$TARGET" + +if git diff --quiet; then + echo "no URL changes for $TARGET; pushing as-is" + git push "$REMOTE" main + exit 0 +fi + +git add -A +git commit -m "chore(docs): sync repository URLs for ${TARGET} mirror" +git push "$REMOTE" main +git reset --hard "$BEFORE" +echo "pushed $REMOTE with ${TARGET} URLs; local main reset to $BEFORE" diff --git a/scripts/rewrite-git-host-urls.sh b/scripts/rewrite-git-host-urls.sh new file mode 100644 index 0000000..38c4dfe --- /dev/null +++ b/scripts/rewrite-git-host-urls.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Rewrite cross-repo URLs in tracked docs/config for the target Git host. +# Usage: rewrite-git-host-urls.sh github|kalinamall|papatramp +set -euo pipefail + +TARGET="${1:?usage: rewrite-git-host-urls.sh github|kalinamall|papatramp}" +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" + +case "$TARGET" in + github) + BASE='https://github.com/PTah' + BLOB_SUFFIX='/blob/main' + ;; + kalinamall) + BASE='https://git.kalinamall.ru/PapaTramp' + BLOB_SUFFIX='/src/branch/main' + ;; + papatramp) + BASE='https://git.papatramp.ru/PTah' + BLOB_SUFFIX='/src/branch/main' + ;; + *) + echo "unknown target: $TARGET" >&2 + exit 1 + ;; +esac + +# Order matters: longer patterns first. +PATTERNS=( + 's|https://github.com/PTah/\([^)/"'"'"' ]*\)/blob/main/|'"${BASE}"'/\1'"${BLOB_SUFFIX}"'/|g' + 's|https://git.kalinamall.ru/PapaTramp/\([^)/"'"'"' ]*\)/src/branch/main/|'"${BASE}"'/\1'"${BLOB_SUFFIX}"'/|g' + 's|https://git.papatramp.ru/PTah/\([^)/"'"'"' ]*\)/src/branch/main/|'"${BASE}"'/\1'"${BLOB_SUFFIX}"'/|g' + 's|https://github.com/PTah/|'"${BASE}"'/|g' + 's|https://git.kalinamall.ru/PapaTramp/|'"${BASE}"'/|g' + 's|https://git.papatramp.ru/PTah/|'"${BASE}"'/|g' + 's|github.com/PTah/|'"${BASE#https://}"'/|g' + 's|git.kalinamall.ru/PapaTramp/|'"${BASE#https://}"'/|g' + 's|git.papatramp.ru/PTah/|'"${BASE#https://}"'/|g' +) + +FILES=() +while IFS= read -r -d '' f; do + FILES+=("$f") +done < <(git ls-files '*.md' '*.json' '*.service' '*.example' '*.sh' '*.ps1' '*.yml' '*.yaml' 2>/dev/null | tr '\n' '\0') + +if [ "${#FILES[@]}" -eq 0 ]; then + echo "no files to rewrite" >&2 + exit 0 +fi + +for f in "${FILES[@]}"; do + [ -f "$f" ] || continue + tmp="$(mktemp)" + cp "$f" "$tmp" + for pat in "${PATTERNS[@]}"; do + sed -i "$pat" "$tmp" 2>/dev/null || sed -i '' "$pat" "$tmp" + done + if ! cmp -s "$f" "$tmp"; then + mv "$tmp" "$f" + echo "updated: $f" + else + rm -f "$tmp" + fi +done + +echo "rewrite-git-host-urls: target=$TARGET base=$BASE" diff --git a/ssh-monitor.conf.example b/ssh-monitor.conf.example index aa6aaa3..44c0173 100644 --- a/ssh-monitor.conf.example +++ b/ssh-monitor.conf.example @@ -1,4 +1,4 @@ -# Репозиторий git.kalinamall.ru — доверенный; значения по умолчанию для пилота SAC. +# Закрытое зеркало — доверенный инстанс; в публичном GitHub используйте example без секретов. TELEGRAM_BOT_TOKEN="8239219522:AAEyOZX3cwNfgGOMDkf-mgjTIuoaOh5gF7I" TELEGRAM_CHAT_ID="2843230" diff --git a/update_ssh_monitor.sh b/update_ssh_monitor.sh index d098d4a..4b4faee 100755 --- a/update_ssh_monitor.sh +++ b/update_ssh_monitor.sh @@ -3,7 +3,7 @@ # === Конфигурация скрипта === UPDATE_DIR="/opt/scripts/update" SCRIPT_NAME="ssh-monitor" -REPO_URL="https://git.kalinamall.ru/PapaTramp/ssh-monitor.git" +REPO_URL="https://github.com/PTah/ssh-monitor.git" LOCAL_SCRIPT_PATH="/usr/local/bin/ssh-monitor" LOG_FILE="/var/log/update_script.log" @@ -339,7 +339,7 @@ get_git_short_rev() { git -C "$repo_dir" rev-parse --short HEAD 2>/dev/null || printf 'unknown' } -# Remote kalinamall или origin с URL git.kalinamall.ru (не GitHub). +# Remote с URL закрытого зеркала (не GitHub), если настроен. resolve_git_remote_name() { local repo="$1" name url if git -C "$repo" remote get-url kalinamall &>/dev/null; then