#!/bin/bash
#
# vmail-stack
# https://git.stack-source.com/msb/vmail-stack
# Copyright (c) 2022 Matthew Saunders Brown <matthewsaundersbrown@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

# load include file
source $(dirname $0)/vmail.sh

help()
{
  thisfilename=$(basename -- "$0")
  echo "$thisfilename"
  echo "Get DKIM info."
  echo ""
  echo "usage: $thisfilename [-d <domain>] [-c] [-h]"
  echo ""
  echo "  -h          Print this help."
  echo "  -d          Domain name to get DKIM info for."
  echo "  -c          CSV - Output in csv format, instead of tabbed table."
  echo ""
  exit
}

vmail:getoptions "$@"

# check for domain
if [[ -n $domain ]]; then
  if [ -f /etc/ssl/dkim/$domain.dkim ]; then
    domains=($domain)
  else
    echo "ERROR: DKIM for $domain does not exist."
    exit 1
  fi
else
  if [[ -d /etc/ssl/dkim/ ]]; then
    domains=(`ls -1 /etc/ssl/dkim/*.dkim 2>/dev/null|cut -d / -f 5|sed 's|.dkim$||g'`)
  fi
fi

if [[ ${#domains[@]} > 0 ]]; then
  # create newline var
  NL=$'\n'
  output="domain selector dkim"
  for domain in "${domains[@]}"
  do
    selector=`cat /etc/ssl/dkim/$domain.selector`
    dkim=`cat /etc/ssl/dkim/$domain.dkim`
    output="$output${NL}$domain $selector $dkim"
  done
  if [[ $csv ]]; then
    echo "$output" | tr " " ","
  else
    echo "$output" | column -t
  fi
else
  # no dkim keys found
  exit 0
fi