#!/bin/sh

# shellcheck disable=SC2119,SC2120

# shellcheck source=../lib/load-configuration
. "${0%/*}/../lib/load-configuration"

# stored functions

# shellcheck disable=SC2016
{
  printf 'SELECT `proc`.`name` FROM `mysql`.`proc` WHERE `proc`.`Db`="buildmaster"' | \
    mysql_run_query | \
    while read -r procedure; do
      printf 'SHOW CREATE PROCEDURE `%s`;\n' "${procedure}"
    done
} | \
  mysql_run_query | \
  sed '
    s/ \(SELECT\|FROM\|\(LEFT \|RIGHT \)\?JOIN\|ON\|WHERE\) /\n\t\1 /g
    s/(SELECT/(\nSELECT/g
  '

# table headers

# shellcheck disable=SC2016
{
  printf 'SHOW TABLES' | \
    mysql_run_query | \
    while read -r table; do
      printf 'SHOW CREATE TABLE `%s`;\n' "${table}"
    done
} | \
  mysql_run_query | \
  sed '
    s/ AUTO_INCREMENT=[0-9]\+ / /g
    s/^ /\t/
  '

# content of "constant" tables
mysqldump --skip-lock-tables 'buildmaster' \
  'architectures' \
  'architecture_compatibilities' \
  'dependency_types' \
  'email_actions' \
  'fail_reasons' \
  'repositories' \
  'repository_moves' \
  'repository_stabilities' \
  'repository_stability_relations' \
  'upstream_repositories' | \
  grep '^INSERT ' | \
  tr '\0\1' '01' | \
  sed '
    s/),(/),\n  (/g
    s/VALUES (/VALUES\n  (/g
  '