#!/bin/bash -eu

# Pack tiles into sqlitedb database
# Based on script written by @ioctl
# Usage: make_sqlitedb <tile dir> <out file>
# Tile format: x-y-z.png, z/x-y.png

# read global configuration and functions
. vmaps.sh

# read local configuration
. ./vmaps.conf

# Remove output file if it exists
rm -f -- "$SQLITEDB"

# Create database
sqlite3 "$SQLITEDB" 'CREATE TABLE tiles (x int, y int, z int, image blob,
  PRIMARY KEY (x,y,z));'

# Find all tiles and put them into db
find -L "$TILE_DIR" -type f -name '*.png' | (
  echo 'PRAGMA journal_mode = OFF; PRAGMA synchronous = 0;'
  while read tile; do

    xyz="$(echo "$tile" | sed -rne '
      s|^.*/([0-9]+)-([0-9]+)-([0-9]+).*$|\1 \2 \3|p
      s|^.*/([0-9]+)/([0-9]+)-([0-9]+).*$|\2 \3 \1|p
    ')"
    read x y z <<< "$xyz"

    echo -n "INSERT INTO tiles (x, y, z, image) VALUES "
    echo     "($x, $y, $z, readfile('$tile'));"
  done )  | sqlite3 "$SQLITEDB"

# Create metadata table
sqlite3 "$SQLITEDB" "CREATE TABLE info (tilenumbering text, minzoom int,
  maxzoom int);"
sqlite3 "$SQLITEDB" "INSERT INTO info (tilenumbering, minzoom, maxzoom)
  VALUES ('', (SELECT min(z) FROM tiles), (SELECT max(z) FROM tiles))"
