Newer
Older
Import / research / match3 / buildSteps.sh
#!/bin/bash
#===============================================================================
#          FILE:  buildSteps.sh
#         USAGE:  ./buildSteps.sh --help
#   DESCRIPTION: Build Step commands - a multi-tool for different custom make commands 
#       CREATED:  02/11/2017
#===============================================================================

# Constructs the SQL statement to rebuild the DB
function BuildSQLStatement()
{
  echo "PRAGMA foreign_keys = ON;"
  echo "BEGIN TRANSACTION;"
  # If the tables could be loaded in any order, then could find
  # all csv files in a given directory instead of needing tables.csv
  cat "db/tables.csv" | while read TABLE
  do
    cat "db/$TABLE.csv" |
    while read HEAD
    do
      # The 1st line of the csv file is the table definition
      echo "CREATE TABLE $TABLE($HEAD);"
      while read LINE
      do
        # The remaining lines are row in the table
        echo "INSERT INTO \"$TABLE\" VALUES($LINE);"
      done
    done
  done
  echo "COMMIT;"
}

# Builds a sqlite3 DB from a collection of CSV files
function BuildDB()
{
  echo "Building DB started"
  rm -rf ./build/gameDB.db
  [ ! -d ./build ] && mkdir ./build
  BuildSQLStatement | sqlite3 ./build/gameDB.db 2>&1 | while read LINE
  do
    # If any error output from executing the SQL statements to create the DB, then print it
    echo $LINE
    # And print the context of the error
    BuildSQLStatement | head -n `echo "$LINE" | sed 's/.*line \([0-9]*\).*/\1/'` | tail -n 1
    # Ensure an invalid DB doesn't remain
    rm -rf ./build/gameDB.db
    echo "Error while building DB"
    exit -1
  done
  echo "Building DB finished"
}

# Print help and usage information
function ShowHelp()
{
  echo "Usage"
  echo "  --buildDB   rebuild the SQLite3 DB from the CSV files"
  echo "  --help      show options"
  exit -1
}

# If no options specified, show the help
if [ $# == 0 ]
then
  ShowHelp
fi

# Do commands
while [ $# != 0 ]
do
  case "$1"
  in
    --buildDB)  BuildDB       ; shift ;;
    --help)     ShowHelp      ; shift ;;
    *)          ShowHelp      ; shift ;;
  esac
done