#!/usr/bin/env bash
# 03-code — atualiza o checkout SOZINHO (fast-forward); roda depois do backup.
set -Eeuo pipefail
# shellcheck source=../lib/common.sh
. "$(dirname "$0")/../lib/common.sh"

phase_begin "03-code"

project_resolve

if ! is_git; then
    warn "checkout sem .git: pull de código pulado (modo teste); o build usa o código presente."
    state_set BEFORE_COMMIT "sem-git"
    state_set AFTER_COMMIT "sem-git"
    phase_end
    exit 0
fi

before="$(git -C "$ROOT" rev-parse HEAD)"
state_set BEFORE_COMMIT "$before"
log "commit antes: ${before}"

if [ "$NO_PULL" = 1 ]; then
    log "git pull desabilitado (--no-pull): usando o código já presente no checkout"
else
    run git -C "$ROOT" fetch --prune --tags
    run git -C "$ROOT" pull --ff-only
fi

after="$(git -C "$ROOT" rev-parse HEAD)"
state_set AFTER_COMMIT "$after"
log "commit depois: ${after}$([ "$before" = "$after" ] && printf ' (sem mudança)')"

phase_end
