#! /bin/bash

set -e

if [[ ${SQLITE:=system} = 'system' ]]; then
    return
fi

DIR=$(pwd)

# Convert to the SQLITE_VERSION_NUMBER format https://sqlite.org/c3ref/c_source_id.html
SQLITE=$(perl -e 'my @v = split /[.]/, shift; printf "%d%02d%02d%02d\n", @v[0..3]' $SQLITE)

# Since 3.7.16.1, the URL includes the year in the path. 
# 3.18.2, 3.18.1, 3.9.3, and 3.7.11 missing. 
# https://sqlite.org/chronology.html
# http://sqlite.1065341.n5.nabble.com/Reverse-Engineering-Project-Download-Old-Versions-tp97096p97154.html
# http://www.linuxfromscratch.org/~thomasp/blfs-book-xsl/server/sqlite.html
if   (( $SQLITE >= 3220000 )); then
    YEAR=2018
elif (( $SQLITE >= 3160000 )); then
    YEAR=2017
elif (( $SQLITE >= 3100000 )); then
    YEAR=2016
elif (( $SQLITE >= 3080800 )); then
    YEAR=2015
elif (( $SQLITE >= 3080300 )); then
    YEAR=2014
elif (( $SQLITE >= 3071601 )); then
    # Earliest release with year in path. 
    YEAR=2013
else
    echo "Unsupported version $SQLITE" >&2
    exit 64
fi

curl -o sqlite.zip https://sqlite.org/$YEAR/sqlite-amalgamation-$SQLITE.zip
unzip -j sqlite.zip -d sqlite
cd sqlite
# Build the CLI. 
gcc shell.c sqlite3.c -lpthread -ldl -o sqlite3
# Build the shared library
gcc -c -fPIC sqlite3.c
gcc -shared -o libsqlite3.so -fPIC sqlite3.o -ldl -lpthread
cd ..

cpanm --notest DBI
curl -o DBD-SQLite.tar.gz https://cpan.metacpan.org/authors/id/I/IS/ISHIGAKI/DBD-SQLite-1.62.tar.gz
mkdir DBD-SQLite
tar -zxf DBD-SQLite.tar.gz --strip-components 1 -C DBD-SQLite
cd DBD-SQLite
perl -i -pe 's/^if\s*\(\s*0\s*\)\s\{/if (1) {/' Makefile. PL
perl Makefile. PL SQLITE_INC=$DIR/sqlite SQLITE_LIB=$DIR/sqlite
make && make install
cd ..

export LD_LIBRARY_PATH=$DIR/sqlite:$LD_LIBRARY_PATH
export PATH=$DIR/sqlite:$PATH
