#!/bin/sh -e
#
# 2011-2014 Steven Armstrong (steven-cdist at armstrong.cc)
#
# This file is part of cdist.
#
# cdist is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cdist is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cdist. If not, see <http://www.gnu.org/licenses/>.
#

if [ -f "$__object/parameter/keyid" ]; then
   keyid="$(cat "$__object/parameter/keyid")"
else
   keyid="$__object_id"
fi
state_should="$(cat "$__object/parameter/state")"
state_is="$(cat "$__object/explorer/state")"

if [ "$state_should" = "$state_is" ]; then
   # nothing to do
   exit 0
fi

keydir="$(cat "$__object/parameter/keydir")"
keyfile="$keydir/$__object_id.gpg"

case "$state_should" in
   present)
      keyserver="$(cat "$__object/parameter/keyserver")"

      if [ -f "$__object/parameter/uri" ]; then
         uri="$(cat "$__object/parameter/uri")"

         if [ -d "$keydir" ]; then
            cat << EOF

curl -s -L \\
    -o "$keyfile" \\
    "$uri"

key="\$( cat "$keyfile" )"

if echo "\$key" | grep -Fq 'BEGIN PGP PUBLIC KEY BLOCK'
then
    echo "\$key" | gpg --dearmor > "$keyfile"
fi

EOF
         else
            # fallback to deprecated apt-key
            echo "curl -s -L '$uri' | apt-key add -"
         fi
      elif [ -d "$keydir" ]; then
         # we need to kill gpg after 30 seconds, because gpg
         # can get stuck if keyserver is not responding.
         # exporting env var and not exit 1,
         # because we need to clean up and kill dirmngr.
         cat << EOF

gpgtmphome="\$( mktemp -d )"

if timeout 30s \\
    gpg --homedir "\$gpgtmphome" \\
        --keyserver "$keyserver" \\
        --recv-keys "$keyid"
then
    gpg --homedir "\$gpgtmphome" \\
        --export "$keyid" \\
        > "$keyfile"
else
    export GPG_GOT_STUCK=1
fi

GNUPGHOME="\$gpgtmphome" gpgconf --kill dirmngr

rm -rf "\$gpgtmphome"

if [ -n "\$GPG_GOT_STUCK" ]
then
    echo "GPG GOT STUCK - no response from keyserver after 30 seconds" >&2
    exit 1
fi

EOF
      else
         # fallback to deprecated apt-key
         echo "apt-key adv --keyserver \"$keyserver\" --recv-keys \"$keyid\""
      fi

      echo "added '$keyid'" >> "$__messages_out"
   ;;
   absent)
      if [ -f "$keyfile" ]; then
         echo "rm '$keyfile'"
      else
         # fallback to deprecated apt-key
         echo "apt-key del \"$keyid\""
      fi

      echo "removed '$keyid'" >> "$__messages_out"
   ;;
esac
