#!/opt/angry-omnibus-toolchain/bin/bash
#
# Copyright:: Copyright 2017 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# This script is based off of https://gist.github.com/cosimo/3760587

set -eou pipefail

function usage() {
  cat <<DOC
Usage: ${0##*/} [DMG_FILE_NAME | RPM_FILE_NAME]

Verify that an rpm is signed or that a dmg contains a signed package.
DOC
}

case "${1:-}" in
  *.dmg | *.rpm)
    package_file="$1"
    ;;
  "-h"|"--help")
    usage
    exit 0
    ;;
  "")
    usage
    exit 1
    ;;
  *)
    echo "Skipping signed package verification. '$1' is not a dmg or rpm."
    exit 0
esac

if [[ ! -f "$package_file" ]]; then
  echo "$package_file does not exist"
  exit 1
fi

case "$package_file" in
  *.dmg)
    echo "--- Checking that $package_file contains a signed package."
    hdiutil detach "/Volumes/chef_software" >/dev/null 2>&1 || true
    hdiutil attach "$package_file" -mountpoint "/Volumes/chef_software"
    pkg_file="$(find "/Volumes/chef_software" -name "*.pkg")"
    result=$(pkgutil --check-signature "$pkg_file" 2>&1 | grep -c "Status: signed")
    hdiutil detach "/Volumes/chef_software"
    if [[ $result -eq 1 ]]; then
      echo "Verified $package_file contains a signed package."
    else
      echo "Exiting with an error because $package_file does not contain a signed package. Check your omnibus project config."
      exit 1
    fi
    ;;
  *.rpm)
    echo "--- Checking that $package_file has been signed."
    if [[ $(rpm -qpi "$package_file" 2>&1 | grep -c "Signature.*Key ID") -eq 1 ]]; then
      echo "Verified $package_file has been signed."
    else
      echo "Exiting with an error because $package_file has not been signed. Check your omnibus project config."
      exit 1
    fi
    ;;
esac