#!/usr/local/bin/bash
#/ Usage: ghe-gc-disable [<option>...] <host>
#/
#/ Helper to disable and drain GC operations on a GitHub Enterprise server.
#/
#/ OPTIONS:
#/   -F	<configfile>		Alternative SSH per-user configuration file.
#/
set -e

# Bring in the backup configuration
. $( dirname "${BASH_SOURCE[0]}" )/ghe-backup-config

while true; do
    case "$1" in
        -F)
            opts="$1 $2"
            shift 2
            ;;
        *)
            host="$1"
            shift
            break
            ;;
    esac
done

# Show usage with no host
[ -z "$host" ] && print_usage

# Touch the sync-in-progress file, disabling GC operations, and wait for all
# active GC processes to finish on the remote side.
echo "
    set -e
    sudo -u git touch '$SYNC_IN_PROGRESS_FILE'
    for i in \$(seq $GHE_GIT_COOLDOWN_PERIOD); do
        # note: the bracket synta[x] below is to prevent matches against the
        # grep process itself.
        if ps axo args | grep -E -e '^git( -.*)? nw-repac[k]( |$)' -e '^git( -.*)? g[c]( |$)' >/dev/null; then
            sleep 1
        else
            exit 0
        fi
    done
    exit 7
" | ghe-ssh $opts "$host" -- /bin/bash || {
    res=$?
    if [ $res = 7 ]; then
        echo "Error: Git GC processes remain after $GHE_GIT_COOLDOWN_PERIOD seconds. Aborting..." 1>&2
    fi
    exit $res
}
