#!/bin/bash
#
# Copyright 2013-2015, SUSE LINUX Products GmbH
#
# 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.
#

set -e

if [ -z "$(type -t die)" ]; then
    # define our own die method as we depend on it; it can be overridden by the
    # sourcer
    die() {
      echo "Error: $@" >&2
      if [ -t 1 ]; then
        exit 1
      fi
    }
fi

skip_check_for_repo () {
    repo="$1"
    for skipped_repo in $REPOS_SKIP_CHECKS; do
        if [ "$repo" = "$skipped_repo" ]; then
            return 0
        fi
    done
    return 1
}

check_key_file () {
  key_file=$1

  local fingerprint
  read -a fingerprint < <(LC_ALL=C gpg --with-fingerprint ${key_file} \
      | grep fingerprint | awk -F= '{print $2}')
  case "${fingerprint[@]}" in
    "4E98 E675 19D9 8DC7 362A 5990 E3A5 C360 307E 3D54") # SLE11 keys
      ;;
    "FEAB 5025 39D8 46DB 2C09 61CA 70AF 9E81 39DB 7C82") # SLES12 key
      ;;
    "BBB0 A65B 9E2D 41F4 5575 4979 4726 6566 F990 41E1") # Devel:Cloud key
      ;;
    *)
      return 1
      ;;
  esac

  return 0
}

check_media_content () {
    repo_name="$1" repo_path="$2" md5="$3"

    if skip_check_for_repo "$repo_name"; then
        echo "Skipping check for $repo_name due to \$REPOS_SKIP_CHECKS"
        return 0
    fi

    if ! [ -e "$repo_path/content.asc" ]; then
        if [ -n "$CROWBAR_FROM_GIT" ]; then
            die "$repo has not been set up yet; please see https://github.com/SUSE/cloud/wiki/Crowbar"
        else
            die "$repo_name has not been set up at $repo_path\n\nPlease check the steps in the installation guide."
        fi
    fi

    if [ -n "$md5" ]; then
        if [ -n "$CROWBAR_FROM_GIT" ]; then
            echo "Skipping md5 check for $repo_name due to \$CROWBAR_FROM_GIT"
        else
            if [ "`md5sum $repo_path/content | awk '{print $1}'`" != "$md5" ]; then
                die "$repo_name does not contain the expected repository ($repo_path/content failed MD5 checksum)"
            fi
        fi
    fi

    if ! check_key_file $repo_path/content.key; then
        die "$repo_name does not contain the expected repository (content does not seem to be signed with the right key)"
    fi
}

check_media_links () {
    MEDIA=$1
    if [[ ! "$(readlink -e ${MEDIA})" =~ ^/srv/tftpboot/.* ]]; then
        die "$MEDIA must exist and any possible symlinks must not point outside /srv/tftpboot/ directory, as otherwise the PXE server can not access it."
    fi
}
