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

PROJECT_DIR="${PROJECT_DIR:-$(pwd)}"
REMOTE_URL="${REMOTE_URL:-git@github.com:LoginManager/networkbots.git}"
DEFAULT_BRANCH="${1:-970566006067}"

GIT_NAME="${GIT_NAME:-LoginManager}"
GIT_EMAIL="${GIT_EMAIL:-login.manager.radius.service@gmail.com}"

NEW_BRANCH=""

log() { printf '%s\n' "$*" >&2; }
need_cmd() { command -v "$1" >/dev/null 2>&1; }

ensure_git_installed() {
  if ! need_cmd git; then
    sudo apt-get update -y
    sudo apt-get install -y git
  fi
}

ensure_identity() {
  git config --global user.name "$GIT_NAME"
  git config --global user.email "$GIT_EMAIL"
}

ensure_project_dir() {
  [ -d "$PROJECT_DIR" ] || { log "[ERROR] PROJECT_DIR not found: $PROJECT_DIR"; exit 1; }
  cd "$PROJECT_DIR"
}

ensure_repo_initialized() {
  if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    return
  fi
  git init
  git checkout -B "$DEFAULT_BRANCH"
}

current_branch() {
  git symbolic-ref --short HEAD 2>/dev/null || echo ""
}

prepare_branch() {
  local cur
  cur="$(current_branch)"
  if [ -z "$cur" ] || [ "$cur" = "HEAD" ]; then
    cur="$DEFAULT_BRANCH"
    git checkout -B "$cur"
  fi
  echo "$cur"
}

ensure_remote() {
  if git remote get-url origin >/dev/null 2>&1; then
    git remote set-url origin "$REMOTE_URL"
  else
    git remote add origin "$REMOTE_URL"
  fi
}

ensure_ssh_ready_if_needed() {
  case "$REMOTE_URL" in
    git@*|ssh://*)
      if ! need_cmd ssh; then
        sudo apt-get install -y openssh-client
      fi
      ssh -o StrictHostKeyChecking=accept-new -T git@github.com 2>&1 || true
    ;;
  esac
}

commit_all_changes() {
  git add -A
  git add -f . 2>/dev/null || true
  if ! git diff --cached --quiet; then
    git commit -m "Server sync: $(date -u +%F' 'T%H:%M:%SZ)"
  fi
}

pull_rebase_or_branch() {
  local branch="$1"
  NEW_BRANCH=""

  if git ls-remote --exit-code --heads origin "$branch" >/dev/null 2>&1; then
    if ! git pull --rebase origin "$branch"; then
      git rebase --abort || true
      NEW_BRANCH="server-sync-$(date +%Y%m%d-%H%M)"
      git checkout -b "$NEW_BRANCH"
      return 1
    fi
  fi

  return 0
}

push_now() {
  local branch="$1"
  git push -u origin "$branch"
}

main() {
  ensure_git_installed
  ensure_identity
  ensure_project_dir
  ensure_repo_initialized
  ensure_remote
  ensure_ssh_ready_if_needed

  local branch
  branch="$(prepare_branch)"

  commit_all_changes

  if pull_rebase_or_branch "$branch"; then
    push_now "$branch"
  else
    [ -n "$NEW_BRANCH" ] || exit 1
    branch="$NEW_BRANCH"
    commit_all_changes
    push_now "$branch"
  fi
}

main "$@"
