#!/bin/bash

# unzip and overwrite
mc_db_dir=/var/appstatic/appstore/mc/
for file in mc.zip
do
    dest_file=$mc_db_dir$file
    unzip -o -d $mc_db_dir $dest_file > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
        echo "unzip $dest_file failed!"
        exit 3
    fi
done
echo "unzip db file success"

# create mc database
db_path=psql
db_password={{getPgDBPassword}}
db_host={{getPgHost}}
db_port={{getPgPort}}
db_user={{getPgDBUser}}
# set password to environment variable
export PGPASSWORD=${db_password}

# if exist return 0, otherwise return 1, parameter 1 is table name, parameter 2 is database name
function table_exist() {
    num=`$db_path -U ${db_user} -h ${db_host} -p ${db_port} -d ${2} -c "SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '${1}';"|awk 'NR==3'`
    if [[ $num -ne 1 ]]; then
        return 1
    fi
}

function create_mc_database() {
  # create database
  for db_name in mc; do
    exists=`$db_path -U ${db_user} postgres -h ${db_host} -p ${db_port} -c "\l"|awk '{print $1}'|grep "^${db_name}"`
    # avoid error when left is empty
    if [[ $exists = ${db_name} ]]
    then
      echo "database ${db_name} has exists"
    else
      $db_path -U ${db_user} postgres -h ${db_host} -p ${db_port} -c "create database ${db_name} with owner={{getPgDBUser}} encoding='UTF8' tablespace=pg_default LC_COLLATE='en_US.UTF-8' LC_CTYPE='en_US.UTF-8' CONNECTION LIMIT=-1 TEMPLATE template0;" > /dev/null 2>&1
      if [ $? -ne 0 ]
      then
        echo "create database ${db_name} failed"
        exit 6
      fi
      echo "create database ${db_name} success"

      $db_path -U ${db_user} postgres -h ${db_host} -p ${db_port} -c "GRANT ALL ON DATABASE ${db_name} TO {{getPgDBUser}};" > /dev/null 2>&1
      if [ $? -ne 0 ]
      then
        echo "grant database ${db_name} failed"
        exit 6
      fi
      echo "grant database ${db_name} success"
    fi
  done
}

# import tables
function import_tables() {
  pg_restore -U ${db_user} -h ${db_host} -p ${db_port} --no-owner --role ${db_user} -d mc -v /var/appstatic/appstore/mc/mc.dump;
}

create_mc_database
import_tables
echo "init pg finish"