#!/bin/sh
# Generates the emoji sequence data (`src/fix/emoji:V62`) and the map built from
# it. Three steps, so the network is never part of a step that has to be
# reproducible:
#
#   sh src/charset/emoji-sequences.sh fetch <dir>
#   sh src/charset/emoji-sequences.sh data <dir> > src/charset/emoji-sequences.txt
#   sh src/charset/emoji-sequences.sh map > src/fix/emoji/emoji-seq.ctrm-map
#
# `data` reads only <dir>; `map` reads only the vendored
# `emoji-sequences.txt` beside this script and the curated table below.
# Same inputs, same bytes. Needs `curl` for `fetch`, and `sha256sum`.
set -eu

VERSION=18.0.0
URL=https://www.unicode.org/Public/$VERSION/emoji
FILES="emoji-sequences.txt emoji-zwj-sequences.txt"

here=$(dirname "$0")

fetch() {
  mkdir -p "$1"
  for file in $FILES; do
    curl -sSfL -o "$1/$file" "$URL/$file"
  done
}

data_header() {
  cat <<EOF
# THE RGI EMOJI SEQUENCES (\`src/fix/emoji:V62\`), GENERATED from Unicode emoji
# data and compiled in (V22). Do not edit a line by hand: regenerate with
# \`src/charset/emoji-sequences.sh\`, which says how.
#
# SOURCE: Unicode emoji $VERSION, from $URL/.
# Unicode License v3; see \`docs/THIRD-PARTY-NOTICES.md\`.
#
EOF
  (cd "$1" && for file in $FILES; do
    printf '#   %s, %s, sha256\n#     %s\n' "$file" \
      "$(sed -n 's/^# Date: //p' "$file")" \
      "$(sha256sum "$file" | cut -d' ' -f1)"
  done)
  cat <<'EOF'
#
# One line per sequence, in upstream order: `<kind> <sequence> [name]`,
# the sequence in the map grammar's notation (`src/fix:I`). Kinds:
# `presentation` (a `Basic_Emoji` code point plus VS16), `keycap`, `flag`
# (two regional indicators), `tag` (a subdivision flag) and `zwj`. A
# `presentation` line maps to nothing -- the builtin map deletes VS16
# (`src/fix/emoji:V60`) -- and is listed so VS16 inside it is no hazard
# (`src/lint/hazard:V63`, B15). LEFT OUT: single-code-point `Basic_Emoji` and
# `RGI_Emoji_Modifier_Sequence`, which hold no hazard to excuse. A flag or
# a presentation carries no name: upstream spells some of those outside
# ASCII (curly quotes), and the sequence itself identifies it.

EOF
}

data() {
  data_header "$1"
  (cd "$1" && cat $FILES) | awk -F';' '
    /^#/ || NF < 3 { next }
    {
      type = $2; gsub(/ /, "", type)
      if (type == "Basic_Emoji" && $1 ~ / FE0F/) kind = "presentation"
      else if (type == "Emoji_Keycap_Sequence") kind = "keycap"
      else if (type == "RGI_Emoji_Flag_Sequence") kind = "flag"
      else if (type == "RGI_Emoji_Tag_Sequence") kind = "tag"
      else if (type == "RGI_Emoji_ZWJ_Sequence") kind = "zwj"
      else next
      n = split($1, cp, " "); seq = ""
      for (i = 1; i <= n; i++) seq = seq (i > 1 ? "+" : "") "U+" cp[i]
      name = $3; sub(/#.*/, "", name)
      gsub(/^ +| +$/, "", name)
      if (kind == "flag" || kind == "presentation") print kind, seq
      else print kind, seq, name
    }'
}

map_header() {
  cat <<'EOF'
# THE EMOJI SEQUENCE MAP (`src/fix/emoji:V62`), GENERATED by
# `src/charset/emoji-sequences.sh map` from the vendored
# `src/charset/emoji-sequences.txt` and compiled in after `../map.ctrm-map`.
# Do not edit a line by hand: regenerate.
#
# One entry per RGI sequence the V60 deletes do not already settle:
#
#   keycap  `<k> U+FE0F U+20E3` -> `<k>`, its digit, `#` or `*`
#   flag    two regional indicators -> the region code they spell (`PL`)
#   tag     U+1F3F4 + tag letters + U+E007F -> `GB-ENG`, `GB-SCT`, `GB-WLS`
#   zwj     the curated single code point below, else the first code point
#
# A flag's code is a `word` entry (`src/fix/words:V51`, V76): it is letters, so
# it is kept apart by a space from a letter, a digit or another flag's
# code beside it (`A` flag-PL `B` -> `A PL B`), never fused (`APLB`).
#
# THE CURATED TABLE, by the upstream name's prefix. UTS #51 revision 31
# (Emoji 18.0), section 2.6 Multi-Person Groupings, lists the single code
# points whose ZWJ sequences make them specific by gender and by skin
# tone; family is the "similar case" it names beside them (2.6.1). EVERY
# variant of a grouping maps to its generic form, gendered and
# skin-toned alike: the code point says "a couple with heart", and a
# writer whose file withholds the sequence is told so by the target.
#
#   family:                      -> U+1F46A FAMILY
#   couple with heart:           -> U+1F491 COUPLE WITH HEART
#   kiss:                        -> U+1F48F KISS
#   men holding hands:           -> U+1F46C TWO MEN HOLDING HANDS
#   women holding hands:         -> U+1F46D TWO WOMEN HOLDING HANDS
#   woman and man holding hands: -> U+1F46B MAN AND WOMAN HOLDING HANDS
#   handshake:                   -> U+1F91D HANDSHAKE
#
# The section's other two, people with bunny ears and people wrestling,
# need no row: their ZWJ forms already open with that code point.
# `people holding hands` (U+1F9D1 ZWJ U+1F91D ZWJ U+1F9D1) has NO single
# code point and is not in the section's list, so it keeps its first
# emoji, U+1F9D1, like any other sequence.
#
# Nothing is guessed beyond it: any other ZWJ sequence keeps its first
# code point, the emoji it was built on (`U+1F468+U+200D+U+1F4BB` -> man).

EOF
}

map() {
  map_header
  awk '
    function hex(s,   v, i, c) {
      v = 0
      for (i = 1; i <= length(s); i++) {
        c = index("0123456789ABCDEF", substr(s, i, 1)) - 1
        v = v * 16 + c
      }
      return v
    }
    function letters(seq, base,   n, p, i, v, out) {
      n = split(seq, p, "+"); out = ""
      for (i = 1; i <= n; i += 2) {
        v = hex(p[i + 1])
        if (v >= base && v < base + 26) out = out sprintf("%c", 65 + v - base)
      }
      return out
    }
    /^#/ || NF < 2 { next }
    $1 == "presentation" { next }
    $1 == "keycap" { split($2, p, "+"); print $2, "U+" p[2]; next }
    $1 == "flag" { print "word", $2, letters($2, hex("1F1E6")); next }
    $1 == "tag" {
      code = letters($2, hex("E0061"))
      print "word", $2, substr(code, 1, 2) "-" substr(code, 3); next
    }
    $1 == "zwj" {
      name = $0; sub(/^[^ ]+ [^ ]+ /, "", name)
      if (name ~ /^family:/) to = "U+1F46A"
      else if (name ~ /^couple with heart:/) to = "U+1F491"
      else if (name ~ /^kiss:/) to = "U+1F48F"
      else if (name ~ /^men holding hands:/) to = "U+1F46C"
      else if (name ~ /^women holding hands:/) to = "U+1F46D"
      else if (name ~ /^woman and man holding hands:/) to = "U+1F46B"
      else if (name ~ /^handshake:/) to = "U+1F91D"
      else { split($2, p, "+"); to = "U+" p[2] }
      print $2, to
    }' "$here/emoji-sequences.txt"
}

case "${1:-}" in
  fetch) fetch "$2" ;;
  data) data "$2" ;;
  map) map ;;
  *) echo "usage: $0 fetch <dir> | data <dir> | map" >&2; exit 2 ;;
esac
