#!/bin/sh -e
#
# 2018 Darko Poljak (darko.poljak at gmail.com)
#
# 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/>.
#

#set -x

if [ ! -f "$__object/parameter/direct" ]; then
    # Nothing here, staged file is used.
    exit 0
fi

state=$(cat "$__object/parameter/state")
destination="/usr/local/bin/consul"

if [ "$state" = "absent" ]; then
    printf 'rm -f "%s"' "$destination"
    exit 0
fi

versions_dir="$__type/files/versions"
version="$(cat "$__object/parameter/version")"
version_dir="$versions_dir/$version"

source=$(cat "$version_dir/source")
source_file_name="${source##*/}"
cksum_should=$(cut -d' ' -f1,2 "$version_dir/cksum")

cat << eof
    tmpdir=\$(mktemp -d --tmpdir="/tmp" "${__type##*/}.XXXXXXXXXX")
    curl -s -L "$source" > "\$tmpdir/$source_file_name"
    unzip -p "\$tmpdir/$source_file_name" > "${destination}.tmp"
    rm -rf "\$tmpdir"

    cksum_is=\$(cksum "${destination}.tmp" | cut -d' ' -f1,2)
    if [ "\$cksum_is" = "$cksum_should" ]; then
        rm -f "${destination}"
        mv "${destination}.tmp" "${destination}"
        chown root:root "$destination"
        chmod 755 "$destination"
    else
        rm -f "${destination}.tmp"
        echo "Failed to verify checksum for $__object_name" >&2
        exit 1
    fi
eof

echo "/usr/local/bin/consul created" >> "$__messages_out"
