#!/bin/bash

# unzip and overwrite
mc_db_dir=/var/appstatic/appstore/mc/
for file in mc.zip tools.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
mysql_path=/var/appstatic/appstore/mc/tools/mysql
db_password={{.db_password}}
db_host={{getMysqlHost}}
db_port={{.db_port}}
db_user={{.db_user}}

# if exist return 0, otherwise return 1, parameter is table name, parameter 2 is database name
function table_exist() {
    num=`$mysql_path -u$db_user -p${db_password} -h${db_host} -P${db_port} -e "SELECT COUNT(*) FROM information_schema.TABLES t WHERE TABLE_SCHEMA='${2}' AND TABLE_NAME = '${1}';"|awk '{print $1}'`
    if [[ $num != "1" ]]; then
        return 1
    fi
}

function create_mc_database() {
  exists=`$mysql_path -u$db_user -p${db_password} -h${db_host} -P${db_port} -e "show databases;"|grep "^mc$"`
  if [[ $exists = "mc" ]]
  then
    echo "database mc has exists"
  else
    $mysql_path -u$db_user -p${db_password} -h${db_host} -P${db_port} -e "CREATE DATABASE mc DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;" > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
      echo "create database mc failed"
      exit 6
    fi
    echo "create database mc success"
  fi
}

# import mc tables
function import_tables() {
    $mysql_path -u$db_user -p${db_password} -h${db_host} -P${db_port} mc < /var/appstatic/appstore/mc/mc.sql > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
      echo "import tables failed"
      exit 7
    else
      echo "import tables success"
    fi
}

create_mc_database
import_tables
echo "init mysql finish"