1#!/bin/bash
2
3set -ex
4
5SOURCE_DIR="$1"
6ASTYLE="$2"
7APIDSL="$3"
8
9# Go to the source root.
10if [ -z "$SOURCE_DIR" ]; then
11  SOURCE_DIR=.
12fi
13cd "$SOURCE_DIR"
14
15if [ -z "$ASTYLE" ] || ! which "$ASTYLE"; then
16  ASTYLE=astyle
17fi
18
19if ! which "$ASTYLE"; then
20  # If we couldn't find or install an astyle binary, don't do anything.
21  echo "Could not find an astyle binary; please install astyle."
22  exit 1
23fi
24
25if ! which "$APIDSL"; then
26  if [ -f ../apidsl/apigen.native ]; then
27    APIDSL=../apidsl/apigen.native
28  else
29    APIDSL=apidsl_curl
30  fi
31fi
32
33TO_JSON='s/\\/\\\\/g;s/\n/\\n/g;s/"/\\"/g;s/^(.*)$/"$1"/'
34FROM_JSON='s/\\"/"/g;s/^"(.*)"$/$1/;s/\\\\/\\/g;s/\\n/\n/g'
35
36apidsl_request() {
37  TMPFILE=$(mktemp /tmp/apidsl.XXXXXX)
38  curl -s -o "$TMPFILE" -X POST --data @<(
39    echo '["Request",'
40    cat "$2"
41    echo ']'
42  ) "https://apidsl.herokuapp.com/$1"
43  if grep '\[1,"' "$TMPFILE" >/dev/null; then
44    echo "Error: $(grep -o '".*"' /tmp/apidsl-$$ | perl -0777 -pe "$FROM_JSON")" >&2
45    rm "$TMPFILE"
46    exit 1
47  fi
48  perl -0777 -pe 's/^\[0,(.*)\]$/$1/' "$TMPFILE"
49  rm "$TMPFILE"
50}
51
52apidsl_curl() {
53  echo "apidsl_curl $*" >&2
54  apidsl_request "c" <(
55    apidsl_request "parse" <(
56      perl -0777 -pe "$TO_JSON" "$1"
57    )
58  ) | perl -0777 -pe "$FROM_JSON"
59}
60
61# Check if apidsl generated sources are up to date.
62set +x
63"$APIDSL" toxcore/LAN_discovery.api.h >toxcore/LAN_discovery.h &
64"$APIDSL" toxcore/crypto_core.api.h >toxcore/crypto_core.h &
65"$APIDSL" toxcore/ping.api.h >toxcore/ping.h &
66"$APIDSL" toxcore/ping_array.api.h >toxcore/ping_array.h &
67"$APIDSL" toxcore/tox.api.h >toxcore/tox.h &
68"$APIDSL" toxav/toxav.api.h >toxav/toxav.h &
69"$APIDSL" toxencryptsave/toxencryptsave.api.h >toxencryptsave/toxencryptsave.h &
70set -x
71
72wait
73wait
74wait
75wait
76wait
77wait
78wait
79
80if grep '<unresolved>' ./*/*.h; then
81  echo "error: some apidsl references were unresolved"
82  exit 1
83fi
84
85readarray -t CC_SOURCES <<<"$(find . '(' -name '*.cc' ')')"
86CC_SOURCES+=(toxcore/crypto_core.c)
87CC_SOURCES+=(toxcore/ping_array.c)
88
89for bin in clang-format-6.0 clang-format-5.0 clang-format; do
90  if which "$bin"; then
91    "$bin" -i -style='{BasedOnStyle: Google, ColumnLimit: 100}' "${CC_SOURCES[@]}"
92    break
93  fi
94done
95
96FIND="find ."
97FIND="$FIND '(' -name '*.[ch]' ')'"
98FIND="$FIND -and -not -name '*.api.h'"
99FIND="$FIND -and -not -wholename './super_donators/*'"
100FIND="$FIND -and -not -wholename './third_party/*'"
101FIND="$FIND -and -not -wholename './toxencryptsave/crypto_pwhash*'"
102
103readarray -t C_SOURCES <<<"$(eval "$FIND")"
104
105"$ASTYLE" -n --options=other/astyle/astylerc "${C_SOURCES[@]}"
106
107git diff --color=always --exit-code
108