#!/usr/bin/env bash
# git-ssh-pull: pull latest from the default SSH remote into current branch
#
# Assumptions:
#   - Your default remote is named "git" and points to your SSH server repo.
#   - You are already in a working copy (not in the bare repo).
#   - You just want the latest files from the remote main branch.
#
# Usage:
#   git-ssh-pull [branch]
#
# Defaults:
#   remote = git
#   branch = main (falls back to master)

set -euo pipefail

REMOTE="git"
BRANCH="${1:-}"

if [[ -z "$BRANCH" ]]; then
    if git rev-parse --verify --quiet "$REMOTE/main" >/dev/null 2>&1; then
        BRANCH="main"
    elif git rev-parse --verify --quiet "$REMOTE/master" >/dev/null 2>&1; then
        BRANCH="master"
    else
        echo "Error: no default branch found for remote '$REMOTE'." >&2
        exit 1
    fi
fi

git fetch "$REMOTE" --quiet
REF="$REMOTE/$BRANCH"

if ! git rev-parse --verify --quiet "$REF" >/dev/null 2>&1; then
    echo "Error: remote ref not found: $REF" >&2
    exit 1
fi

if ! git rev-parse --verify --quiet "$BRANCH" >/dev/null 2>&1; then
    git checkout -B "$BRANCH" --track "$REF"
else
    git checkout "$BRANCH"
    git merge --ff-only "$REF"
fi

echo "Pulled latest '$BRANCH' from remote '$REMOTE'."
