#!/bin/bash -eu

# Pack tiles into Osmand sqlitedb database
# Based on script written by @ioctl
# Tile format: x-y-z.png, z/x-y.png

# see: https://osmand.net/docs/technical/osmand-file-formats/osmand-sqlite/

# read global configuration and functions
. vmaps.sh ||:

# read local configuration
. ./vmaps.conf ||:

if [ "$TILE_DIR" = "" ]; then
  echo "vmaps_pack_sqlitedb: TILE_DIR is not set, exiting"
  exit
fi

if [ "$SQLITEDB" = "" ]; then
  echo "vmaps_pack_sqlitedb: SQLITEDB is not set, exiting"
  exit
fi

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

echo "Creating $SQLITEDB"

# Find all tiles and put them into db
find -L "$TILE_DIR" -type f -name '*.png' | (

  echo 'CREATE TABLE tiles (x int, y int, z int, image blob, PRIMARY KEY (x,y,z));'
  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
  # Create metadata table
  echo "CREATE TABLE info (tilenumbering text, minzoom int, maxzoom int);"
  echo "INSERT INTO info (tilenumbering, minzoom, maxzoom)
        VALUES ('', (SELECT min(z) FROM tiles), (SELECT max(z) FROM tiles))"
) | sqlite3 "$SQLITEDB"

