#!/bin/bash
# SPDX-License-Identifier: EPL-1.0
##############################################################################
# Copyright (c) 2018 The Linux Foundation and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
##############################################################################

last_update() {
  # Print when the newest change matching the Gerrit query URL $1 was last
  # updated, or nothing if none matches. Gerrit answers a query for an
  # account it does not know with HTTP 400 "Account ... not found", which
  # counts as no match. Any other failure exits 1: a Gerrit that cannot be
  # reached, or answers with another error, would make every committer
  # look inactive.
  local response status changes
  if ! response=$(curl --silent --show-error -G -w '\n%{http_code}' "$1"); then
    echo "ERROR: Could not query $gerriturl" >&2
    exit 1
  fi
  status="${response##*$'\n'}"
  changes="${response%$'\n'*}"
  if [ "$status" == "400" ] && grep -qi "not found" <<< "$changes"; then
    return 0
  fi
  if [ "$status" != "200" ]; then
    echo "ERROR: Gerrit at $gerriturl answered with status code $status: $changes" >&2
    exit 1
  fi
  # Read the date of the updated field, whether or not Gerrit pretty-prints
  # its JSON; by default it sends each change on one line.
  sed -n 's/.*"updated": *"\([^ "]*\).*/\1/p' <<< "$changes"
}

datediff() {
  d1=$(date -d "$1" +%s)
  d2=$(date -d "$2" +%s)
  echo $(( (d1 - d2) / 86400 )) days ago
}

main() {

  echo "checking $gerriturl participation for group $group"
  echo

  # Read the whole group first: a lookup that fails must fail the script,
  # not report on an empty or partial list of committers.
  local committers
  if ! committers=$(LEGACY_CLI=1 lftools-uv ldap csv "$group"); then
    echo "ERROR: LDAP lookup of $group failed" >&2
    exit 1
  fi

  currentdate=$(date +%Y-%m-%d)
  while read -r line; do

    [ -n "$line" ] || continue
    currenetgroup="$group"
    group="$(echo "$line" | awk -F"," '{print $1}')"
    id="$(echo "$line" | awk -F"," '{print $2}')"
    fullname="$(echo "$line" | awk -F"," '{print $3}')"
    email="$(echo "$line" | awk -F"," '{print $NF}')"

    if [[ "$group" != "$currenetgroup" ]]; then
      echo
      echo "####### $group #####"
    fi

    time_ago=$(date -d "-12 month" +%Y-%m-%d)

    updated=$(last_update \
      "https://$gerriturl/changes/?q=reviewedby:$id+after:$time_ago%20OR%20owner:$id+after:$time_ago&n=1") \
      || exit 1

    if  [[ -z $updated ]]; then

     updated=$(last_update "https://$gerriturl/changes/?q=reviewedby:$id%20OR%20owner:$id&n=1") || exit 1

      if  [[ -z $updated ]]; then
       echo -n "  ERROR $id, $fullname, $email has no activity "

       registered_on=$(ssh -n -p 29418 "$gerritssh" "gerrit gsql -c \"select registered_on from accounts where full_name = \\\"$fullname\\\" \" ")
       whenreg=$(echo "$registered_on" | awk '{ print $3, $4 }' | awk '{print $1}'| sed s,\(,,g)
         if [[ $whenreg == 0 ]]; then
           echo "AND USER NEVER REGISTERED"
         else
           echo -n "REGISTERED ON $whenreg "
           datediff "$currentdate" "$whenreg"
         fi
      else
       echo -n "  WARNING $id, $fullname, $email inactive since $updated "
           datediff "$currentdate" "$updated"
      fi

    else
     echo "  OK $id, $fullname, $email last submission or review $updated"
    fi

  done <<< "$committers"

}


usage() {
cat << EOF
This program searches gerrit by email for user participation
Email list can be built with 'ldap-lookup'
Program outputs users who have not used gerrit at all, or in the last 6 months
users from this list can be slated to have their access revoked.

If you encounter: "Can't contact LDAP server"

you will need to add:
TLS_CACERT /path/to/ca.crt in /etc/openldap/ldap.conf
ca.crt can be found on any collab system in /etc/ipa/ca.crt

Usage:
 $1  target gerrit url
 $2  target ldap group

ex: $0 gerrit.opnfv.org/gerrit opnfv-gerrit-releng-submitters
EOF
}

if [[ $# -eq 0 ]] ; then usage "$@"
  exit 1
fi

gerriturl="$1"
gerritssh=${gerriturl%/*}
group="$2"
main
