#!/usr/bin/env bash
# Push code to Windows production via rsync over SSH.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=common.sh
source "${SCRIPT_DIR}/common.sh"

run_rsync_push() {
  [[ -f "${SSH_KEY_PATH}" ]] || die "SSH key not found at ${SSH_KEY_PATH}. Run: ./deploy.sh setup-ssh"

  # Fișiere create de composer ca root — ilizibile pentru rsync
  for dir in vendor storage bootstrap/cache; do
    [[ -d "${PROJECT_ROOT}/${dir}" ]] && chmod -R u+rX "${PROJECT_ROOT}/${dir}" 2>/dev/null || true
  done

  local -a rsync_opts=(
    --archive
    --no-owner
    --no-group
    --omit-dir-times
    --verbose
    --human-readable
    --itemize-changes
    --exclude-from="${DEPLOY_DIR}/rsync-excludes.txt"
  )

  if [[ "${RSYNC_COMPRESS}" == "true" ]]; then
    rsync_opts+=(--compress)
  fi
  if [[ "${RSYNC_DELETE}" == "true" ]]; then
    rsync_opts+=(--delete)
  fi
  if [[ "${DRY_RUN}" == "true" ]]; then
    rsync_opts+=(--dry-run)
    warn "DRY RUN — no files will be changed on the server"
  fi

  mapfile -t env_filters < <(build_rsync_filter_args)
  rsync_opts+=("${env_filters[@]}")

  local ssh_wrapper="/tmp/app-main-updater-rsync-ssh.sh"
  {
    echo '#!/usr/bin/env bash'
    echo 'exec ssh \'
    if [[ -n "${SSH_CONFIG_FILE:-}" && -f "${SSH_CONFIG_FILE}" ]]; then
      printf '  -F %q \\\n' "${SSH_CONFIG_FILE}"
    else
      printf '  -i %q \\\n' "${SSH_KEY_PATH}"
      printf '  -p %q \\\n' "${DEPLOY_PORT}"
      echo '  -o BatchMode=yes \'
      echo '  -o PasswordAuthentication=no \'
      echo '  -o IdentitiesOnly=yes \'
      if [[ -f "${SSH_KNOWN_HOSTS}" ]]; then
        printf '  -F /dev/null \\\n'
        printf '  -o UserKnownHostsFile=%q \\\n' "${SSH_KNOWN_HOSTS}"
      fi
    fi
    echo '  "$@"'
  } > "${ssh_wrapper}"
  chmod 700 "${ssh_wrapper}"
  rsync_opts+=(-e "${ssh_wrapper}")

  log "Syncing ${PROJECT_ROOT} -> $(remote_target)"
  set +e
  rsync "${rsync_opts[@]}" "${PROJECT_ROOT}/" "$(remote_target)"
  local rsync_ec=$?
  set -e

  if [[ ${rsync_ec} -eq 0 ]]; then
    log "Rsync finished"
    return 0
  fi

  if [[ ${rsync_ec} -eq 23 ]]; then
    warn "Rsync exit 23 (unele fișiere/atribute omise — de obicei permisiuni locale sau cache)"
    if [[ "${DRY_RUN}" == "true" ]]; then
      warn "Dry-run: continuăm — conexiunea SSH și sync-ul principal funcționează"
      return 0
    fi
    warn "Deploy real: continuăm (cod 23 non-fatal pentru deploy Laravel)"
    return 0
  fi

  die "Rsync failed with exit code ${rsync_ec}"
}

run_remote_post_deploy() {
  [[ -n "${REMOTE_POST_DEPLOY}" ]] || return 0
  log "Running remote post-deploy hook..."
  ssh_cmd "${REMOTE_POST_DEPLOY}"
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  load_config
  run_rsync_push
  if [[ "${DRY_RUN}" != "true" ]] && [[ "${RUN_REMOTE_TASKS_AFTER_SYNC:-false}" == "true" ]]; then
    "${SCRIPT_DIR}/remote-tasks.sh" all
  fi
fi
