# ASSERT: this script must be executed with effective group membership in one of:
#           [ adm systemd-journal wheel ]


readonly HACKERS_LIB_DIR=/usr/lib/parabola-hackers


FindHackerBySshSha() # (hacker_ssh_sha)
{
  local hacker_ssh_sha=$1
  local hacker_login

  for hacker_login in $(${HACKERS_LIB_DIR}/meta-cat --group git | cut -d ',' -f 2)
  do  ${HACKERS_LIB_DIR}/ssh-list-authorized-keys ${hacker_login} | \
      while read ssh_key
      do    ssh_sha=$(ssh-keygen -l -E sha256 -f - <<<${ssh_key} | cut -d ' ' -f 2)

            [[ "${ssh_sha}" == "${hacker_ssh_sha}" ]] && echo ${hacker_login} && break
      done                                                                    && break
  done
}

LastHackerLogin()
{
  local last_ssh_sha="$(journalctl --unit=sshd.service --since=-24h 2> /dev/null | \
                        grep 'Accepted publickey for git from '                  | \
                        tail -n 1                                                | \
                        sed 's|.*ssh2: .* \(SHA256:.*\)$|\1|'                      )"
  local hacker_login=$(FindHackerBySshSha ${last_ssh_sha})

  if   [[ -n "${hacker_login}" ]]
  then echo ${hacker_login}
  else echo "can not determine the last hacker login" >&2
  fi

  [[ -n "${this_hacker_login}" ]]
}


LastHackerLogin
