Deliver centralized role management feature
[portal.git] / deliveries / wait-for.sh
1 #!/bin/sh
2 # https://github.com/Eficode/wait-for.git
3 # MIT License
4
5 TIMEOUT=15
6 QUIET=0
7
8 echoerr() {
9   if [ "$QUIET" -ne 1 ]; then printf "%s\n" "$*" 1>&2; fi
10 }
11
12 usage() {
13   exitcode="$1"
14   cat << USAGE >&2
15 Usage:
16   $cmdname host:port [-t timeout] [-- command args]
17   -q | --quiet                        Do not output any status messages
18   -t TIMEOUT | --timeout=timeout      Timeout in seconds, zero for no timeout
19   -- COMMAND ARGS                     Execute command with args after the test finishes
20 USAGE
21   exit "$exitcode"
22 }
23
24 wait_for() {
25   command="$*"
26   for i in `seq $TIMEOUT` ; do
27     nc -z "$HOST" "$PORT" > /dev/null 2>&1
28     result=$?
29     if [ $result -eq 0 ] ; then
30       if [ "$QUIET" -ne 1 ]; then echo "Operation succeeded on try $i"; fi
31       if [ -n "$command" ] ; then
32         exec $command
33       fi
34       exit 0
35     fi
36     sleep 1
37   done
38   echo "Operation timed out" >&2
39   exit 1
40 }
41
42 while [ $# -gt 0 ]
43 do
44   case "$1" in
45     *:* )
46     HOST=$(printf "%s\n" "$1"| cut -d : -f 1)
47     PORT=$(printf "%s\n" "$1"| cut -d : -f 2)
48     shift 1
49     ;;
50     -q | --quiet)
51     QUIET=1
52     shift 1
53     ;;
54     -t)
55     TIMEOUT="$2"
56     if [ "$TIMEOUT" = "" ]; then break; fi
57     shift 2
58     ;;
59     --timeout=*)
60     TIMEOUT="${1#*=}"
61     shift 1
62     ;;
63     --)
64     shift
65     break
66     ;;
67     --help)
68     usage 0
69     ;;
70     *)
71     echoerr "Unknown argument: $1"
72     usage 1
73     ;;
74   esac
75 done
76
77 if [ "$HOST" = "" -o "$PORT" = "" ]; then
78   echoerr "Error: you need to provide a host and port to test."
79   usage 2
80 fi
81
82 wait_for "$@"