#! /bin/sh
# Build and install the previous release of flex.
#
# A git checkout of flex has no scan.c, and generating it takes a flex that
# is already installed. A release tarball ships a scan.c, so it builds with
# a C compiler, make and GNU m4 (flex runs m4 itself). Run this once, then put
# PREFIX/bin on your PATH before running ./autogen.sh and ./configure in the
# checkout.
#
# The tarball is checked against a pinned SHA-256 and against the signature
# of the flex release key, whose fingerprint is written below. That needs gpg.
#
# Usage: tools/bootstrap-flex PREFIX

set -e

# The release to bootstrap from, signed by the flex release key (2.6.5 is the
# first release it signed). This only needs to change when the flex source
# can no longer be built by this release or when this release is withdrawn:
# update both lines, to a release signed by the key.
version=2.6.5
sha256=4dfb3d6095c0cd58f050dd66fa132ad52c118c5ae26a4bddd916557720920769
# The fingerprint of the release key's primary key. The signature must have
# been made by this key (or one of its subkeys); a key that comes with the
# download proves nothing.
key_fpr=56D664C70CC2364CF5164914B7DFE8BB6C241FED

if test $# -ne 1; then
    echo "usage: $0 PREFIX" >&2
    exit 2
fi
prefix=$1

tarball=flex-$version.tar.gz
base=https://github.com/westes/flex/releases/download/v$version
url=$base/$tarball

workdir=$(mktemp -d)
trap 'rm -rf "$workdir"' EXIT
cd "$workdir"

if ! command -v gpg >/dev/null 2>&1; then
    echo "error: need gpg to check the signature of $tarball" >&2
    exit 1
fi

fetch() {
    if command -v curl >/dev/null 2>&1; then
        curl -fsSLO "$1"
    elif command -v wget >/dev/null 2>&1; then
        wget -q "$1"
    else
        echo "error: need curl or wget to download $tarball" >&2
        exit 1
    fi
}

echo "Downloading $url"
fetch "$url"
fetch "$url.sig"
fetch "$base/flex-release-key.asc"

if command -v sha256sum >/dev/null 2>&1; then
    actual=$(sha256sum "$tarball" | cut -d ' ' -f 1)
else
    actual=$(shasum -a 256 "$tarball" | cut -d ' ' -f 1)
fi
if test "$actual" != "$sha256"; then
    echo "error: $tarball has sha256 $actual, expected $sha256" >&2
    exit 1
fi

# Import the key into a keyring of its own and require a good signature
# made by the key with the pinned fingerprint. VALIDSIG ends with the
# fingerprint of the primary key.
GNUPGHOME=$workdir/gnupg
export GNUPGHOME
mkdir -m 700 "$GNUPGHOME"
gpg --batch --quiet --import flex-release-key.asc
if ! gpg --batch --status-fd 1 --verify "$tarball.sig" "$tarball" 2>/dev/null |
        grep -q "^\[GNUPG:\] VALIDSIG .* $key_fpr\$"; then
    echo "error: $tarball is not signed by the flex release key $key_fpr" >&2
    exit 1
fi

tar -xzf "$tarball"
cd "flex-$version"
./configure --prefix="$prefix"
make
make install

echo "Installed flex $version in $prefix. Add $prefix/bin to your PATH."
