#!/bin/zsh
set -e

echo "Creating tmpfs directories..."
for i in /usr/lib/gcc /usr/lib/python2.7; do
	mkdir -p $i
	mount -t tmpfs tmpfs $i
done

echo "Downloading and installing required packages..."
pacman -Sy patch gcc make libusb-compat pcsclite

echo "Downloading GnuPG..."
wget ftp://ftp.gnupg.org/gcrypt/gnupg/gnupg-2.1.1.tar.bz2
if [ "$(sha256sum gnupg-2.1.1.tar.bz2 | awk '{ print $1 }')" = \
	"70ecd01d2875db62624c911c2fd815742f50aef5492698eb3bfc09a08690ce49" ]
then
	echo "Verification successful!"
else
	echo "Verification failed!"
	exit 1
fi
tar xfvj gnupg-2.1.1.tar.bz2
cd gnupg-2.1.1

echo "Downloading and applying patch 1..."
wget "http://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=commitdiff_plain;h=bdc8efbdd124d836c36cf482216e375421f72891;hp=76140141699b545f7a988bf5fc101063917e8ce3" -O patch1
if [ "$(sha256sum patch1 | awk '{ print $1 }')" = \
	"3ecc120d1c8e17df431bdc63dd54bf06dcf518eb9242e607c466876dc4183c4b" ]
then
	echo "Verification successful!"
else
	echo "Verification failed!"
	exit 1
fi
patch -p1 <patch1

echo "Downloading and applying patch 2..."
wget "http://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=commitdiff_plain;h=9453d645d4a489f038829c80343c124fff62d635;hp=6c87d1ce66d8e93e6c0f16c06116e9179f6158ba" -O patch2
if [ "$(sha256sum patch2 | awk '{ print $1 }')" = \
	"b06d5d608128a0c8de9044f568e19591251aba530d9d26588321367fcda57b0c" ]
then
	echo "Verification successful!"
else
	echo "Verification failed!"
	exit 1
fi
patch -p1 <patch2

echo "Downloading and applying patch 3..."
wget "http://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=commitdiff_plain;h=f6d3c6e5263d84b94ebe13df9ff39b02109a2acb;hp=6eebc56687935f3e993eac374b9f4cc5ad3bcf2b" -O patch3
if [ "$(sha256sum patch3 | awk '{ print $1 }')" = \
	"94d99159d0833b2adf5d205d8ece157b084c705bec449916b45e1f2f2e7f0502" ]
then
	echo "Verification successful!"
else
	echo "Verification failed!"
	exit 1
fi
patch -p1 <patch3

echo "Configuring GnuPG..."
./configure --prefix=/usr

echo "Building and installing GnuPG..."
make
make install

echo "All done!"
