#!/bin/sh
# Replaces the gateway containers of the compose stack one at a time, so
# clocks are never turned away: `docker compose up -d` after a new image
# would recreate every replica at once.
#
# Load the new image and set HOURADVANTAGE_IMAGE in .env to it first. For each
# gateway container running now: start one more replica from that image and
# the current settings, wait until it is ready and HAProxy has it in
# rotation, then stop the old one (SIGTERM: /api/ready turns 503, HAProxy
# takes it out within about 4 s, it drains for 6 s, then closes) and remove
# it. The number of replicas is the same at the end as at the start.
#
#   ./rolling-update.sh [-f docker-compose.yml -f docker-compose.external-db.yml]
#   (a downloaded copy is not executable: `sh rolling-update.sh`, or `chmod +x` it)
#
# The project is COMPOSE_PROJECT_NAME, or houradvantage. Only it is touched.
set -eu

here=$(cd "$(dirname "$0")" && pwd)
project=${COMPOSE_PROJECT_NAME:-houradvantage}
timeout=${TIMEOUT:-120}
files=""
while [ $# -gt 0 ]; do
    case "$1" in
        -f) shift; files="$files -f $here/$1" ;;
        *) echo "unknown argument: $1" >&2; exit 2 ;;
    esac
    shift
done
[ -n "$files" ] || files="-f $here/docker-compose.yml"

compose() {
    # shellcheck disable=SC2086
    docker compose -p "$project" --project-directory "$here" $files "$@"
}

gateways() {
    compose ps -q gateway | sort
}

# Servers HAProxy has UP in every device backend (be_http_<port>, one per
# device port): the fewest UP in any of them.
in_rotation() {
    compose exec -T haproxy sh -c 'echo "show stat" | nc 127.0.0.1 9999' 2>/dev/null |
        awk -F, '$1 ~ /^be_http_/ && $2 != "BACKEND" { n[$1] += ($18 ~ /^UP/) }
                 END { m = 0; first = 1; for (b in n) { if (first || n[b] < m) m = n[b]; first = 0 } print m }'
}

ready() {
    docker exec "$1" hourd healthcheck --ready >/dev/null 2>&1
}

# The replica started and not yet in rotation: removed again if the update
# stops before it is, so that a failed one is not left behind to restart for
# ever. The old ones are untouched until a new one is in rotation.
starting=""

abandon() {
    [ -n "$starting" ] || return 0
    echo "last lines of $starting:" >&2
    docker logs --tail 3 "$starting" >&2 2>&1 || true
    docker rm -f "$starting" >/dev/null 2>&1 || true
    echo "removed $starting; the $count gateway container(s) running before are still serving, untouched" >&2
    starting=""
}

# wait_for <what> <command...>
wait_for() {
    what=$1
    shift
    waited=0
    until "$@"; do
        waited=$((waited + 1))
        if [ "$waited" -gt $((timeout * 2)) ]; then
            echo "timed out waiting for $what" >&2
            abandon
            exit 1
        fi
        sleep 0.5
    done
}

rotation_is() { [ "$(in_rotation)" -eq "$1" ]; }
rotation_at_least() { [ "$(in_rotation)" -ge "$1" ]; }

old=$(gateways)
count=$(echo "$old" | grep -c . || true)
[ "$count" -gt 0 ] || { echo "no gateway containers are running in project $project" >&2; exit 1; }
echo "replacing $count gateway container(s), one at a time"

for id in $old; do
    before=$(gateways)
    compose up -d --no-deps --no-recreate --scale "gateway=$((count + 1))" gateway >/dev/null 2>&1
    new=$(gateways | while read -r c; do echo "$before" | grep -qx "$c" || echo "$c"; done)
    [ "$(echo "$new" | grep -c .)" -eq 1 ] || { echo "expected one new gateway container, got: $new" >&2; exit 1; }
    starting=$new
    name=$(docker inspect -f '{{.Name}}' "$new" | sed 's|^/||')
    wait_for "$name to be ready" ready "$new"
    wait_for "HAProxy to put $name in rotation" rotation_at_least $((count + 1))
    old_name=$(docker inspect -f '{{.Name}}' "$id" | sed 's|^/||')
    starting=""
    echo "  $name is in rotation; stopping $old_name"
    # The gateway drains (6 s) before it closes and stops in about 20 s at the
    # most; compose gives it 40 s.
    docker stop -t 40 "$id" >/dev/null
    docker rm "$id" >/dev/null
    wait_for "HAProxy to drop $old_name" rotation_is "$count"
done
echo "done: $count gateway container(s) replaced"
