#! /usr/bin/env bash
# shellcheck source=tool/test/.ctx

ec=0

(
  desc='Create and rename a file without overwriting an existing file'
  read -r -d '' expect << .
[
  {
    "effect_type": "create",
    "path_name": "s/self/live@d",
    "path_type": "watcher"
  },
  {
    "effect_type": "create",
    "path_name": "d/a",
    "path_type": "file"
  },
  {
    "effect_type": "rename",
    "path_name": "d/a",
    "path_type": "file",
    "associated": {
      "effect_type": "rename",
      "path_name": "d/b",
      "path_type": "file"
    }
  },
  {
    "effect_type": "destroy",
    "path_name": "s/self/die@d",
    "path_type": "watcher"
  }
]
.

  echo -n "$desc ... "

  . "$(dirname "$0")/.ctx"

  actual=$(
    watch-async "$testdir" -ms 800 > "$testdir.json"
    touch a
    mv a b
    wait # for the watcher
    show-events "$testdir" | without-effect-time
  )

  check-result "$expect" "$actual"
)
ec=$((ec + $?))

(
  desc='Create and rename a file, overwriting an existing file'
  read -r -d '' expect << .
[
  {
    "effect_type": "create",
    "path_name": "s/self/live@d",
    "path_type": "watcher"
  },
  {
    "effect_type": "create",
    "path_name": "d/a",
    "path_type": "file"
  },
  {
    "effect_type": "create",
    "path_name": "d/b",
    "path_type": "file"
  },
  {
    "effect_type": "rename",
    "path_name": "d/a",
    "path_type": "file",
    "associated": {
      "effect_type": "rename",
      "path_name": "d/b",
      "path_type": "file"
    }
  },
  {
    "effect_type": "destroy",
    "path_name": "s/self/die@d",
    "path_type": "watcher"
  }
]
.

  echo -n "$desc ... "

  . "$(dirname "$0")/.ctx"

  actual=$(
    watch-async "$testdir" -ms 800 > "$testdir.json"
    touch a b
    # todo:
    # Otherwise, on Darwin, b will have a creation event
    # after the rename, and will miss the one above.
    [ "$(uname -s)" = Darwin ] && sleep 0.2
    portable-destructive-rename a b
    wait # for the watcher
    show-events "$testdir" | without-effect-time
  )

  check-result "$expect" "$actual"
)
ec=$((ec + $?))

exit "$ec"
