#!/bin/sh

BIN_GIT=${BIN_GIT:-git}

log_info()    { text=$1; shift; printf "%b%s ${text}%b\n" "$BLUE"   "$INFO_EM" "$@" "$NC"; }
log_success() { text=$1; shift; printf "%b%s ${text}%b\n" "$GREEN"  "$SUCC_EM" "$@" "$NC"; }
log_warning() { text=$1; shift; printf "%b%s ${text}%b\n" "$YELLOW" "$WARN_EM" "$@" "$NC"; }
log_error()   { text=$1; shift; printf "%b%s ${text}%b\n" "$RED"    "$ERRO_EM" "$@" "$NC"; }
log_step()    { text=$1; shift; printf "%b%s ${text}%b\n" "$PURPLE" "$STEP_EM" "$@" "$NC"; }

# --- CLI flags ---
# --local  / --no-remote-build  -> disable remote build
# env REMOTE_BUILD=1|0 sets default (1 if unset)

REMOTE_BUILD=${REMOTE_BUILD:-1}

# Parse leading flags
while [ $# -gt 0 ]; do
  case "$1" in
    --local|--no-remote-build)   REMOTE_BUILD=0; shift ;;
    --) shift; break ;;
    *) break ;;
  esac
done

REMOTE_FLAG=
[ "$REMOTE_BUILD" -eq 1 ] && REMOTE_FLAG="--remote-build"

# Deploy a specific system
deploy_system() {
  sys="$1"; shift
  log_step "Deploying ${sys} system..."
  nix run nixpkgs#deploy-rs -- -s $REMOTE_FLAG \
    "${LOCAL_DIR}#${sys}_x86_64-linux.system" \
    -- --impure --verbose "$@"
}

# Deploy both systems
deploy_both_systems() {
  deploy_system master "$@"
  deploy_system proxy "$@"
}

log_step "Detecting local directories..."
if git_root=$($BIN_GIT rev-parse --show-toplevel 2>/dev/null); then
  LOCAL_DIR="$git_root"
  log_success "Found git root: ${WHITE}$LOCAL_DIR${NC}"
else
  LOCAL_DIR="$(pwd)"
  log_warning "Not in git repo, using current dir: ${WHITE}$LOCAL_DIR${NC}"
  read -p "Are you realy want continue? (y/n): " CONTINUE
  [ "$CONTINUE" = "y" ] || { log_error "Aborting..."; exit 0; }
fi

$BIN_GIT add .
set -a
# shellcheck disable=SC1091
[ -f "$LOCAL_DIR/.env" ] && . "$LOCAL_DIR/.env"
set +a

# First positional after flags is the target (optional)
DEPLOY_TARGET="$1"
shift 2>/dev/null || true

case "$DEPLOY_TARGET" in
  master) deploy_system master "$@" ;;
  proxy)  deploy_system proxy  "$@" ;;
  test)   deploy_system 'test' "$@" ;;
  ""|*)   # default: both
          [ -n "$DEPLOY_TARGET" ] && set -- "$DEPLOY_TARGET" "$@"
          deploy_both_systems "$@"
          ;;
esac
