#!/bin/bash

# 配置用户信息
git config --global user.name "maxwellxzy" 
git config --global user.email "maxwellxzy@gmail.com"

# 设置仓库相关变量
ORIGIN_URL="git@git.disbaidu.com:maxwell/note.git" # 主仓库
GITHUB_URL="git@github.com:maxwellxzy/note.git" # GitHub 仓库
ORIGIN_BRANCH="main" # 主仓库分支
GITHUB_BRANCH="main" # GitHub 仓库分支
SCRIPT_PATH=$(cd "$(dirname "$0")"; pwd -P)
LOG_FILE="$SCRIPT_PATH/auto_sync_to_github.log"
timestamp=$(date "+%Y-%m-%d %H:%M:%S")

# 日志记录函数
log() {
  echo "[$timestamp] $1" >> "$LOG_FILE"

}
log "-------------[$timestamp]--------------"
# 切换到脚本目录
cd "$SCRIPT_PATH" || { log "Failed to change directory to $SCRIPT_PATH"; exit 1; }

# 验证 SSH 连接
check_ssh() {
  local url=$1
  if ! ssh -T "$(echo $url | cut -d: -f1)"; then
    log "SSH connection to $url failed."
    return 1
  fi
  return 0
}

#log "Checking SSH..."
#check_ssh "$ORIGIN_URL" || exit 1
#check_ssh "$GITHUB_URL" || exit 1

# 比较这两个仓库的指定分支的 HEAD 是否一致
log "Checking HEADs..."
ORIGIN_HEAD=$(git ls-remote "$ORIGIN_URL" "$ORIGIN_BRANCH" | cut -f1) || { log "Failed to get HEAD of $ORIGIN_URL:$ORIGIN_BRANCH"; exit 1; }
GITHUB_HEAD=$(git ls-remote "$GITHUB_URL" "$GITHUB_BRANCH" | cut -f1) || { log "Failed to get HEAD of $GITHUB_URL:$GITHUB_BRANCH"; exit 1; }
log "ORIGIN_HEAD: $ORIGIN_HEAD"
log "GITHUB_HEAD: $GITHUB_HEAD"
if [[ "$ORIGIN_HEAD" == "$GITHUB_HEAD" ]]; then
  log "SAME HEADs on branch $ORIGIN_BRANCH. Exiting..."
  exit 0
fi

# 处理仓库更新和同步
rm -rf "$SCRIPT_PATH/origin" || { log "Failed to remove old origin directory"; exit 1; }
git clone "$ORIGIN_URL" "$SCRIPT_PATH/origin" || { log "Failed to clone origin repository"; exit 1; }
cd "$SCRIPT_PATH/origin" || { log "Failed to change directory to origin"; exit 1; }

# 推送到 GitHub
log "Pushing to GitHub..."
git push -f "$GITHUB_URL" "$GITHUB_BRANCH" || { log "Failed to push to GitHub"; }
  log "Push to GitHub successful."

# 清理
log "Cleaning up..."
cd "$SCRIPT_PATH" || { log "Failed to change directory to $SCRIPT_PATH"; exit 1; }
rm -rf "$SCRIPT_PATH/origin" || log "Failed to remove origin directory after sync."
# 验证 GitHub 仓库 HEAD 是否更新
log "Checking GitHub HEAD..."
GITHUB_HEAD=$(git ls-remote "$GITHUB_URL" "$GITHUB_BRANCH" | cut -f1)
log "GITHUB_HEAD: $GITHUB_HEAD"
log "ORIGIN_HEAD: $ORIGIN_HEAD"
if [[ "$ORIGIN_HEAD" != "$GITHUB_HEAD" ]]; then
  log "HEADs not updated on GitHub. Exiting..."
  exit 1
fi

log "Sync to GitHub successful."

exit 0
