#!/usr/bin/env bash
# dsflow - designer-side DesignSync flow
#
#   dsflow sync             populate workspace from the green working tag
#   dsflow edit F...        start editing F from Trunk:Latest; lock only if F is a hot file
#   dsflow add F...         register brand-new files for check-in
#   dsflow status           modified files, and any that went stale on Trunk
#   dsflow precheckin       refresh to Trunk:Latest, run sanity on all configs, write stamp
#   dsflow checkin -m MSG   verify stamp + freshness, check in, log it
#   dsflow rebase F...      the one sanctioned merge path (invalidates the stamp)
#   dsflow claim F...       ad hoc lock on a non-hot file (big refactor, etc.)
#   dsflow release F...     drop an ad hoc lock without checking in
#
# Run from the workspace root. Site-specific settings and all dssc output
# parsing live in dsflow.conf.
set -euo pipefail

WS_ROOT="$(pwd)"
CONF="${DSFLOW_CONF:-$WS_ROOT/flow/dsflow.conf}"
[[ -f $CONF ]] || { echo "dsflow: config not found: $CONF" >&2; exit 2; }
# shellcheck source=/dev/null
source "$CONF"

STATE="$WS_ROOT/.dsflow"
STAMP="$STATE/sanity.stamp"
NEW_FILES="$STATE/new_files"
mkdir -p "$STATE"; touch "$NEW_FILES"

die()  { echo "dsflow: $*" >&2; exit 1; }
info() { echo "dsflow: $*"; }
now()  { date -u +%Y-%m-%dT%H:%M:%SZ; }

is_hot()         { grep -qxF "$1" "$HOT_FILES" 2>/dev/null; }
modified_files() { ds_list_modified | sort -u; }
new_files()      { sort -u "$NEW_FILES"; }
all_changes()    { { modified_files; new_files; } | sort -u; }

# Modified files whose Trunk:Latest moved past the version we started from.
# These are the only files that can ever need a merge.
stale_files() {
  local f
  while read -r f; do
    [[ -n $f ]] || continue
    [[ "$(ds_base_version "$f")" == "$(ds_latest_version "$f")" ]] || echo "$f"
  done < <(modified_files)
}

content_hash() {
  local files; mapfile -t files < <(all_changes)
  ((${#files[@]})) || { echo none; return; }
  sha1sum "${files[@]}" | sha1sum | cut -d' ' -f1
}

require_fresh() {
  local stale; stale="$(stale_files)"
  [[ -z $stale ]] || die "these files were checked in by someone else since you started:
$stale
Run: dsflow rebase <file>   (then precheckin again)"
}

cmd_sync() {
  info "populating from green tag '$WORKING_TAG' (local edits are kept)"
  dssc pop -rec -version "$WORKING_TAG" .
}

cmd_edit() {
  (($#)) || die "usage: dsflow edit FILE..."
  local f holder
  for f; do
    if modified_files | grep -qxF "$f"; then info "already editing: $f"; continue; fi
    holder="$(ds_lock_holder "$f")"
    [[ -z $holder || $holder == "$USER" ]] || die "$f is locked by $holder - coordinate first"
    if is_hot "$f"; then
      dssc co -lock -version "$TRUNK_SEL" "$f"
      info "LOCKED (hot file): $f - check in soon, others are blocked"
    else
      dssc co -nolock -version "$TRUNK_SEL" "$f"
      info "editing from Latest, no lock: $f"
    fi
  done
}

cmd_add() {
  (($#)) || die "usage: dsflow add FILE..."
  local f
  for f; do [[ -f $f ]] || die "no such file: $f"; echo "$f" >> "$NEW_FILES"; done
  sort -u -o "$NEW_FILES" "$NEW_FILES"
  rm -f "$STAMP"
}

cmd_status() {
  info "changes in this workspace:"
  all_changes | sed 's/^/  /'
  local stale; stale="$(stale_files)"
  if [[ -n $stale ]]; then echo "STALE (rebase needed):"; echo "$stale" | sed 's/^/  /'
  else info "no stale files"; fi
  if [[ -f $STAMP ]]; then
    # shellcheck source=/dev/null
    source "$STAMP"
    [[ $stamp_hash == "$(content_hash)" ]] && info "sanity stamp: valid ($stamp_when)" \
                                         || info "sanity stamp: out of date"
  else info "sanity stamp: none"; fi
}

cmd_precheckin() {
  [[ -n "$(all_changes)" ]] || die "nothing to check in"
  require_fresh
  info "refreshing unmodified files to $TRUNK_SEL (local edits kept)"
  dssc pop -rec -version "$TRUNK_SEL" .
  local cfg log
  for cfg in $SANITY_CONFIGS; do
    log="$STATE/sanity_$cfg.log"
    info "sanity [$cfg] -> $log"
    if ! run_sanity "$cfg" >"$log" 2>&1; then
      rm -f "$STAMP"; die "sanity FAILED for $cfg - see $log"
    fi
  done
  cat > "$STAMP" <<EOF
stamp_hash=$(content_hash)
stamp_epoch=$(date +%s)
stamp_when=$(now)
stamp_configs="$SANITY_CONFIGS"
EOF
  info "sanity PASSED on: $SANITY_CONFIGS - ready to check in"
}

cmd_checkin() {
  local msg="" o
  while getopts m: o; do case $o in m) msg=$OPTARG ;; *) die "usage: dsflow checkin -m MSG" ;; esac; done
  [[ -n $msg ]] || die "usage: dsflow checkin -m \"comment\""
  [[ -f $STAMP ]] || die "no sanity stamp - run: dsflow precheckin"
  # shellcheck source=/dev/null
  source "$STAMP"
  [[ $stamp_hash == "$(content_hash)" ]] || die "files changed since sanity - rerun precheckin"
  [[ $stamp_configs == "$SANITY_CONFIGS" ]] || die "sanity config list changed - rerun precheckin"
  (( $(date +%s) - stamp_epoch <= MAX_STAMP_AGE )) || die "sanity stamp is too old - rerun precheckin"
  require_fresh

  local mods news
  mapfile -t mods < <(modified_files)
  mapfile -t news < <(new_files)
  ((${#mods[@]})) && dssc ci -comment "$msg" "${mods[@]}"
  ((${#news[@]})) && dssc ci -new -comment "$msg" "${news[@]}"

  printf '%s\t%s\t%s\t%s\n' "$(now)" "$USER" "$stamp_hash" "${mods[*]} ${news[*]}" >> "$CHECKIN_LOG"
  : > "$NEW_FILES"; rm -f "$STAMP"
  info "checked in. CI will promote '$WORKING_TAG' once the full sanity passes."
}

cmd_rebase() {
  (($#)) || die "usage: dsflow rebase FILE..."
  local f
  for f; do dssc pop -merge -version "$TRUNK_SEL" "$f"; done
  rm -f "$STAMP"
  info "merged. Resolve any conflict markers, then: dsflow precheckin"
}

cmd_claim()   { (($#)) || die "usage: dsflow claim FILE..."; dssc co -lock -version "$TRUNK_SEL" "$@"; }
cmd_release() { (($#)) || die "usage: dsflow release FILE..."; ds_unlock "$@"; }

sub="${1:-}"; shift || true
case "$sub" in
  sync|edit|add|status|precheckin|checkin|rebase|claim|release) "cmd_$sub" "$@" ;;
  *) sed -n '2,15p' "$0"; exit 1 ;;
esac
