#!/bin/bash
set -e

# This script modifies the install.sh script for domains and keys other than
# those used by the primary opensource releases.
#
# You can provide `url`, `yum_url`, `apt_url` and optionally `gpg_fingerprint`
# or `GPG_KEYID` as environment variables, or the defaults for open source are used.
#
# The lower-case variables are substituted into install.sh.
#
# gpg_fingerprint and GPG_KEYID are optional, defaulting to the opensource release
# key ("releasedocker"). Other GPG_KEYIDs will require you to mount a volume with
# the correct contents to /root/.gnupg.
#
# It outputs the modified `install.sh` file to $DOCKER_RELEASE_DIR (default: $DEST)
#
# Example usage:
#
# docker run \
# --rm \
# --privileged \
# -e "GPG_KEYID=deadbeef" \
# -e "GNUPGHOME=/root/.gnupg" \
# -v $HOME/.gnupg:/root/.gnupg \
# -v $(pwd):/go/src/github.com/docker/docker/bundles \
# "$IMAGE_DOCKER" \
# hack/make.sh install-script

: ${DOCKER_RELEASE_DIR:=$DEST}
: ${GPG_KEYID:=releasedocker}

DEFAULT_URL="https://get.docker.com/"
DEFAULT_APT_URL="https://apt.dockerproject.org"
DEFAULT_YUM_URL="https://yum.dockerproject.org"
DEFAULT_GPG_FINGERPRINT="58118E89F3A912897C070ADBF76221572C52609D"

: ${url:=$DEFAULT_URL}
: ${apt_url:=$DEFAULT_APT_URL}
: ${yum_url:=$DEFAULT_YUM_URL}
if [[ "$GPG_KEYID" == "releasedocker" ]] ; then
	: ${gpg_fingerprint:=$DEFAULT_GPG_FINGERPRINT}
fi

DEST_FILE="$DOCKER_RELEASE_DIR/install.sh"

bundle_install_script() {
	mkdir -p "$DOCKER_RELEASE_DIR"

	if [[ -z "$gpg_fingerprint" ]] ; then
		# NOTE: if no key matching key is in /root/.gnupg, this will fail
		gpg_fingerprint=$(gpg --with-fingerprint -k "$GPG_KEYID" | grep "Key fingerprint" | awk -F "=" '{print $2};' | tr -d ' ')
	fi

	cp hack/install.sh "$DEST_FILE"
	sed -i.bak 's#^url=".*"$#url="'"$url"'"#' "$DEST_FILE"
	sed -i.bak 's#^apt_url=".*"$#apt_url="'"$apt_url"'"#' "$DEST_FILE"
	sed -i.bak 's#^yum_url=".*"$#yum_url="'"$yum_url"'"#' "$DEST_FILE"
	sed -i.bak 's#^gpg_fingerprint=".*"$#gpg_fingerprint="'"$gpg_fingerprint"'"#' "$DEST_FILE"
	rm "${DEST_FILE}.bak"
}

bundle_install_script
