#!/usr/bin/env bash
set -euo pipefail

HOST="${STUDIO_HOST:-john@58.38.22.103}"
REMOTE_ROOT="${STUDIO_REMOTE_ROOT:-/Users/john/Project}"

say() {
  printf '\n[%s] %s\n' "$(date +%H:%M:%S)" "$*"
}

say "103 主机与运行目录"
ssh -o BatchMode=yes -o ConnectTimeout=15 "${HOST}" \
  "hostname; printf 'REMOTE_ROOT=%s\n' '${REMOTE_ROOT}'; ls '${REMOTE_ROOT}' | sed -n '1,80p'"

say "103 运行服务"
ssh -o BatchMode=yes -o ConnectTimeout=15 "${HOST}" \
  "launchctl list | egrep 'memind|plaza|goose|adm' || true"

say "103 生产目录 git 概况"
ssh -o BatchMode=yes -o ConnectTimeout=15 "${HOST}" '
for d in /Users/john/Project/Memind /Users/john/Project/memind_adm; do
  echo "==$(basename "$d")=="
  echo "branch=$(git -C "$d" rev-parse --abbrev-ref HEAD)"
  echo "commit=$(git -C "$d" rev-parse --short HEAD)"
  echo "dirty=$(git -C "$d" status --short | wc -l | tr -d " ")"
done'

say "103 数据库指向"
ssh -o BatchMode=yes -o ConnectTimeout=15 "${HOST}" '
for f in /Users/john/Project/Memind/.env /Users/john/Project/memind_adm/.env; do
  echo "==${f}=="
  egrep "^(DATABASE_URL|MYSQL_HOST|MYSQL_PORT|MYSQL_DATABASE|H5_PORT|ADM_API_PORT)" "$f" || true
done'

say "本地与 103 HEAD 对比"
remote_memind="$(ssh -o BatchMode=yes -o ConnectTimeout=15 "${HOST}" "cd /Users/john/Project/Memind && git rev-parse --short HEAD")"
remote_adm="$(ssh -o BatchMode=yes -o ConnectTimeout=15 "${HOST}" "cd /Users/john/Project/memind_adm && git rev-parse --short HEAD")"
local_memind="$(git -C "$(cd "$(dirname "$0")/.." && pwd)" rev-parse --short HEAD)"
local_adm="$(git -C /Users/john/PycharmProjects/test/test-memindadm rev-parse --short HEAD)"
printf 'local_memind=%s remote_memind=%s\n' "${local_memind}" "${remote_memind}"
printf 'local_memindadm=%s remote_memindadm=%s\n' "${local_adm}" "${remote_adm}"
