#!/bin/ksh
###############################################################################
#  Script Name : make_distdb
#
#  Overview 
#     This script provides the simple interface to construct of 
#     distributor db.
#     Following jobs are executed step by step.
#    
# STEP 0 : read the parameters 
# STEP 1 : create the dist db 
# STEP 2 : Start the dist db server
# STEP 3 : set the password
# STEP 4 : create tables
# STEP 5 : read the master info
# STEP 6 : read the environment info
#
# NOTES
#    This script should be expanded when the repl_agent can process multiple
#    slaves & masters
#
###############################################################################

###############################################################################
# function : print out usage info
###############################################################################
usage() {
  exec_name=`basename $0`
  echo "usage: $exec_name dist_db_name [-p dba_passwd] " 1>&2
  exit 1
}

###############################################################################
# function : print message
###############################################################################
print_mes_h() {
  case $1 in
    STEP1)
      echo "  STEP 1 : ¹èÆ÷ DB¸¦ »ý¼º ÁßÀÔ´Ï´Ù. Àá½Ã¸¸ ±â´Ù·Á ÁÖ½Ê½Ã¿À."
      ;;
    STEP2)
      echo "  STEP 2 : ¹èÆ÷ DB ¼­¹ö¸¦ ±¸µ¿ÇÏ°í ÀÖ½À´Ï´Ù. Àá½Ã¸¸ ±â´Ù·Á ÁÖ½Ê½Ã¿À."
      ;;
    STEP3)
      echo "  STEP 3 : ¹èÆ÷ DB ÀÇ DBA °èÁ¤À» ¼³Á¤ÇÕ´Ï´Ù."
      ;;
    STEP4)
      echo "  STEP 4 : º¹Á¦¿¡ ÇÊ¿äÇÑ Å×ÀÌºíµéÀ» »ý¼ºÇÕ´Ï´Ù."
      ;;
    STEP5)
      echo "  STEP 5 : º¹Á¦ ´ë»ó ¸¶½ºÅÍ DB Á¤º¸¸¦ ÀÔ·ÂÇÕ´Ï´Ù."
      ;;
    STEP51)
      printf "       1. ¸¶½ºÅÍ DBÀÇ ÀÌ¸§À» ÀÔ·ÂÇÏ½Ã¿À. >> "
      ;;
    STEP52)
      echo "       2. ¸¶½ºÅÍ DB°¡ À§Ä¡ÇÑ È£½ºÆ®ÀÇ IP ÁÖ¼Ò¸¦ ÀÔ·ÂÇÏ½Ã¿À."
      echo "          - IP ÁÖ¼Ò°¡ ºÎÁ¤È®ÇÏ°Ô ÀÔ·ÂµÇ¸é º¹Á¦°¡ ¼öÇàµÇÁö ¾Ê½À´Ï´Ù."
      printf "                ¸¶½ºÅÍ DB IP >> "
      ;;
    STEP53)
      printf "       3. º¹Á¦¼­¹ö(repl_server)°¡ »ç¿ëÇÏ´Â TCP/IP Æ÷Æ®¹øÈ£¸¦ ÀÔ·Â ÇÏ½Ã¿À.>> "
      ;;
    STEP54)
      echo "       4. º¹Á¦¿¡ ÇÊ¿äÇÑ º¹Á¦·Î±×À» ÀúÀåÇÒ µð·ºÅä¸®¸¦ ÀÔ·ÂÇÏ½Ã¿À. "
      printf "           $CurDir ÀÌ¸é ¿£ÅÍ Å°¸¦ ÀÔ·ÂÇÏ½Ã¿À. >> "
      ;;
    STEP6)
      echo "  STEP 6 : º¹Á¦ È¯°æ º¯¼ö¸¦ ¼³Á¤ÇÕ´Ï´Ù."
      ;;
    STEP61)
      echo "       1. ÃßÀû ·Î±×¸¦ ÀúÀåÇÒ µð·ºÅä¸®¸¦ ÀÔ·ÂÇÏ½Ã¿À.  "
      printf "           $CurDir ÀÌ¸é ¿£ÅÍ Å°¸¦ ÀÔ·ÂÇÏ½Ã¿À. >> "
      ;;
    STEP62)
      echo "       2. ¿¡·¯·Î±×¸¦ ÀúÀåÇÒ µð·ºÅä¸®¸¦ ÀÔ·ÂÇÏ½Ã¿À. "
      printf "           $CurDir ÀÌ¸é ¿£ÅÍ Å°¸¦ ÀÔ·ÂÇÏ½Ã¿À. >> "
      ;;
    STEP63)
      printf "       3. º¹Á¦ ¿¡ÀÌÀüÆ®(repl_agent)ÀÇ »óÅÂ Ç¥½Ã¸¦ À§ÇÑ TCP/IP Æ÷Æ®¹øÈ£¸¦ ÀÔ·ÂÇÏ½Ã¿À.>> "
      ;;
    STEP64)
      printf "       4. º¹Á¦ Áö¿¬ ½Ã°£ log ÆÄÀÏÀÇ Å©±â(line ¼ö)¸¦ ÀÔ·ÂÇÏ½Ã¿À. >> "
      ;;
  esac
}

print_mes_e() {
  case $1 in
    STEP1)
      echo "  STEP 1 : Creating the distributor database...."
      ;;
    STEP2)
	  echo "  STEP 2 : Starting up the server for distributor.. "
      ;;
    STEP3)
	  echo "  STEP 3 : Setting the DBA account of distributor database.."
      ;;
    STEP4)
      echo "  STEP 4 : Creating the objects for replication... "
      ;;
    STEP5)
      echo "  STEP 5 : Please provide information of the master databases ..."
      ;;
    STEP51)
      printf "       1. Please enter the name of the master database >> "
      ;;
    STEP52)
      echo "       2. Please enter the IP address of the master database."
      echo "          - Replication would not work without correct IP address."
      printf "                IP address of the master >> "
      ;;
    STEP53)
      printf "       3. Please enter the TCP/IP port number of the repl_server >> "
      ;;
    STEP54)
      echo "       4. Please enter the directory path of copy log."
      printf "         If the target directory is $CurDir, just strike enter.. >> "
      ;;
    STEP6)
      echo "  STEP 6 : Configuring the replication parameters.."
      ;;
    STEP61)
      echo "       1. Please enter the directory path of trail log. "
      printf "         If the target directory is $CurDir, just strike enter.. >> "
      ;;
    STEP62)
      echo "       2. Please enter the directory path of error log. "
      printf "         If the target directory is $CurDir, just strike enter.. >> "
      ;;
    STEP63)
      printf "       3. Please enter the TCP/IP port number for information of repl_agent status. >> "
      ;;
    STEP64)
      printf "       4. Please enter the file size(line number) of replication delay time log. >> "
      ;;
  esac
}

print_mes() {
  if [ "$kor_yn" = "yes" ]
  then
    print_mes_h $1 $2
  else
    print_mes_e $1 $2
  fi
}

print_error_h() {
  case $1 in
    err_check_env)
      printf " << ERROR >> È¯°æ º¯¼ö ¼³Á¤À» È®ÀÎÇÏ½Ã±â ¹Ù¶ø´Ï´Ù."
      echo "$2"
      ;;
    err_cant_create_dist)
      printf " << ERROR >> ¹èÆ÷ DB¸¦ »ý¼ºÇÒ ¼ö ¾ø½À´Ï´Ù."
      echo $2
      ;;
    err_cant_start_dist)
      echo " << ERROR >> ¹èÆ÷ DB¸¦ ±¸µ¿ÇÒ ¼ö ¾ø½À´Ï´Ù."
      ;;
    err_no_master_name)
      echo " << ERROR >> ¸¶½ºÅÍ DB ÀÌ¸§ÀÌ ÀÔ·ÂµÇÁö ¾Ê¾Ò½À´Ï´Ù."
      ;;
    err_directory_error)
      echo " << ERROR >> ÀÔ·ÂÇÏ½Å µð·ºÅä¸®°¡ Á¸ÀçÇÏÁö ¾Ê½À´Ï´Ù."
      ;;
    err_invalid_input)
      echo " << ERROR >> ÀÔ·ÂÇÏ½Å °ªµéÀ» ´Ù½Ã ÇÑ¹ø È®ÀÎÇØ ÁÖ¼¼¿ä. "
      ;;
    err_copylog_dir)
      echo " << ERROR >> º¹Á¦·Î±× ÀúÀå µð·ºÅä¸®°¡ ¼³Á¤µÇÁö ¾Ê¾Ò½À´Ï´Ù."
      ;;
    err_ip_addr)
      echo " << ERROR >> IP ÁÖ¼Ò°¡ ÀÔ·ÂµÇÁö ¾Ê¾Ò½À´Ï´Ù."
      ;;
    err_port_num)
      echo " << ERROR >> º¹Á¦¼­¹ö(repl_server)ÀÇ Æ÷Æ®¹øÈ£°¡ ÀÔ·ÂµÇÁö ¾Ê¾Ò½À´Ï´Ù. "
      ;;
  esac
  echo "#######################################################################"
  echo " ¿À·ù·Î ÀÎÇØ º¹Á¦ È¯°æ ±¸¼º ÀÛ¾÷À» Á¾·áÇÕ´Ï´Ù."
  echo "#######################################################################"
}

print_error_e() {
  case $1 in
    err_check_env)
      printf " << ERROR >> Check the environment variable."
      echo "$2"
      ;;
    err_cant_create_dist)
      printf " << ERROR >> Can't create the distributor database."
      echo $2
      ;;
    err_cant_start_dist)
      printf " << ERROR >> Can't start up the distributor database."
      ;;
    err_no_master_name)
      echo " << ERROR >> Master database name should be provided."
      ;;
    err_directory_error)
      echo " << ERROR >> Directory does not exists."
      ;;
    err_invalid_input)
      echo " << ERROR >> Invalid input value."
      ;;
    err_copylog_dir)
      echo " << ERROR >> Directory name of copy log should be provided."
      ;;
    err_ip_addr)
      echo " << ERROR >> IP address should be provided."
      ;;
    err_port_num)
      echo " << ERROR >> TCP port number of the repl_server should be provided."
      ;;
  esac
  echo "#######################################################################"
  echo " Stopped by error..."
  echo "#######################################################################"
}

print_error() {
  if [ "$kor_yn" = "yes" ]
  then
    print_error_h $1 $2
  else
    print_error_e $1 $2
  fi

  if [ "$was_created" -eq 1 ]
  then
    $rootdir/bin/cubrid server stop $dist_db_name > /dev/null
    $rootdir/bin/cubrid deletedb $dist_db_name  > /dev/null
  fi
  exit 1
}


###############################################################################
# trying to get root
###############################################################################
RootDir="CUBRID"
was_created=0

for i in $RootDir
do
  seevar="echo \$$i"
  rootdir=`eval $seevar`
  if [ -n "$rootdir" ]
  then
    break;
  fi
done

if [ -z "$rootdir" ]
then
  print_error err_check_env " - CUBRID"
fi

rootDir="CUBRID_DATABASES"

for i in $RootDir
do
  seevar="echo \$$i"
  rootdir_db=`eval $seevar`
  if [ -n "$rootdir_db" ]
  then
    break;
  fi
done

if [ -z "$rootdir_db" ]
then
  print_error err_check_env " - CUBRID_DATABASES"
fi

lang="$CUBRID_LANG"
if [ -z "$lang" ]
then
  lang="en_US"
fi

kor_yn="no"
if [ ! -z "$lang" ] && [ "$lang" = "ko_KR.euckr" ]
then
  kor_yn="yes"
fi

if [ "$kor_yn" = "yes" ]
then
echo "#########################################################################"
echo "#                                                                       #"
echo "#                CUBRID º¹Á¦ È¯°æ ±¸¼º : º¹Á¦ ¿¡ÀÌÀüÆ® ±¸¼º             #"
echo "#                                                                       #"
echo "#   º¹Á¦ È¯°æÀ» ±¸¼ºÇÏ´Â ÀÛ¾÷Àº ´ÙÀ½°ú °°Àº ¼ø¼­·Î ÁøÇàµÇ¾î¾ß ÇÕ´Ï´Ù.   #"
echo "#        1. º¹Á¦ ¿¡ÀÌÀüÆ® ±¸¼º (make_distdb ½ºÅ©¸³Æ® ±¸µ¿)              #"
echo "#        2. ¸¶½ºÅÍ DB ÀüÃ¼ ¹é¾÷ (cubrid backup À¯Æ¿¸®Æ¼±¸µ¿)            #"
echo "#        3. ¸¶½ºÅÍ DB ¹é¾÷º» º¹»ç (¸¶½ºÅÍ DB È£½ºÆ®->½½·¹ÀÌºê DB È£½ºÆ®)#"
echo "#        4. ½½·¹ÀÌºê DB ±¸Ãà (make_slavedb ½ºÅ©¸³Æ® ±¸µ¿)               #"
echo "#        5. º¹Á¦ ¼­¹ö±¸µ¿ (repl_server À¯Æ¿¸®Æ¼ ±¸µ¿)                   #"
echo "#        6. º¹Á¦ ¿¡ÀÌÀüÆ® ±¸µ¿ (repl_agent À¯Æ¿¸®Æ¼ ±¸µ¿)               #"
echo "#                                                                       #"
echo "#     NOTE: ¸¶½ºÅÍ DB¸¦ ¹é¾÷¹Þ´Â ½ÃÁ¡Àº ½½·¹ÀÌºê DB ±¸Ãà½ÃÁ¡ ÀÌÀüÀÌ¸é   #"
echo "#           ¾ðÁ¦µçÁö »ó°ü¾øÀ¸³ª  ¿Â¶óÀÎ¹é¾÷À» ÇÏ´Â °æ¿ì °¡±ÞÀû          #"
echo "#           ½½·¹ÀÌºê DB ±¸Ãà ¹Ù·Î Àü¿¡ ¼öÇàÇÏ½Ã¸é ÃÊ±â º¹Á¦¿¡  ¼Ò¿äµÇ´Â #"
echo "#           ½Ã°£À» Àý¾àÇÏ½Ç ¼ö ÀÖ½À´Ï´Ù.                                #"
echo "#           ÇÊ¿äÇÑ ¹é¾÷ ÆÄÀÏÀº ´ÙÀ½°ú °°½À´Ï´Ù.                         #"
echo "#                          -  master_db_name.bk_vinf                    #"
echo "#                          -  master_db_name.bk0v???                    #"
echo "#                                                                       #"
echo "#   º¹Á¦ ¿¡ÀÌÀüÆ®°¡ ÀÛ¾÷ÇÏ±â À§ÇØ ÇÊ¿äÇÑ ¹èÆ÷ DB¸¦ »ý¼ºÇÕ´Ï´Ù.          #"
echo "#      - ¹èÆ÷ DB´Â ¹Ýµå½Ã DBA °èÁ¤À¸·Î µ¿ÀÛÇØ¾ß ÇÏ¹Ç·Î DBA °èÁ¤À»       #"
echo "#        ÁöÁ¤ÇÏ½Ã±â ¹Ù¶ø´Ï´Ù.                                           #"
echo "#                                                                       #"
echo "#   CUBRID ¿¡¼­´Â ÇÏ³ªÀÇ ½½·¹ÀÌºê DB ´ç ÇÏ³ªÀÇ ¹èÆ÷ DB°¡ »ý¼ºµË´Ï´Ù.    #"
echo "#      - ¹èÆ÷ DB ¹× º¹Á¦ ¿¡ÀÌÀüÆ®(repl_agent)´Â ¸¶½ºÅÍ DB°¡ À§Ä¡ÇÑ      #"
echo "#        È£½ºÆ®¿¡¼­ ¼öÇàÇÏ½Ã¸é º¹Á¦ ÀÛ¾÷ÀÌ ´À¸®°Ô ÁøÇàµÉ ¼ö ÀÖ½À´Ï´Ù.   #"
echo "#                                                                       #"
echo "#   Ctrl-C µîÀ¸·Î ºñÁ¤»óÀûÀ¸·Î ½ºÅ©¸³Æ®¸¦ Áß´ÜÇÏ´Â °æ¿ì¿¡´Â             #"
echo "#   cubrid server stop/cubrid delete µîÀÇ  À¯Æ¿¸®Æ¼¸¦ ÀÌ¿ëÇÏ¿©          #"
echo "#   ¹èÆ÷ DB¸¦ »èÁ¦ÇÑ ÈÄ ´Ù½Ã ¼öÇàÇÏ½Ê½Ã¿À.                              #"
echo "#########################################################################"
else
echo "#########################################################################"
echo "#                                                                       #"
echo "#                Configuration of the Replication Agent                 #"
echo "#                                                                       #"
echo "#   To configure the replication environment,                           #"
echo "#        1. Configure the replication agent (using make_distdb script)  #"
echo "#        2. Back up the master database (using cubrid backup)           #"
echo "#        3. Copy the backup files to the slave site                     #"
echo "#        4. Construct the slave database (using make_slavedb script)    #"
echo "#        5. Start the repl_server at the master site                    #"
echo "#        6. Start the repl_agent at the slave site                      #"
echo "#                                                                       #"
echo "#   NOTE1: You have to back up the master database before constructing  #"
echo "#          the slave databases. If you back up the master database just #"
echo "#          before constructing the slave database, you can save the     #"
echo "#          time to synchronize the master database and slave database.  #"
echo "#          Following files should be copied to the slave site..         #"
echo "#                          -  master_db_name.bk_vinf                    #"
echo "#                          -  master_db_name.bk0v???                    #"
echo "#                                                                       #"
echo "#   NOTE2: To configure the distributor database, DBA account is        #"
echo "#          is necessary. Please provide the DBA account.                #"
echo "#                                                                       #"
echo "#   NOTE3: A distributor database should be created per slave database. #"
echo "#          Please create the distributor database and start up the      #"
echo "#          repl_agent at the slave site for the best performance.       #"
echo "#                                                                       #"
echo "#   When you stop this script using Ctrl-C, please retry again after    #"
echo "#   deleting the distributor database using 'cubrid server stop'after   #"
echo "#   then 'cubrid delete'.                                               #"
echo "#########################################################################"
fi

###############################################################################
# STEP 0 : read the parameters
###############################################################################
dist_db_name=$1

while [ $# -ne 0 ]
do
  case $2 in
     -p)
        shift
        passwd=$2
        ;;
     *)
        ;;
  esac
  shift
done

#check inputs
if [ -z "$dist_db_name" ]
then
  usage
fi

CurDir=`eval pwd`

###############################################################################
# STEP 1 : create the dist db
###############################################################################
print_mes STEP1
$rootdir/bin/cubrid createdb $dist_db_name 2> .distdb.tmp
if [ "$?" -ne 0 ]
then
  print_error err_cant_create_dist $result
fi
was_created=1
###############################################################################
# STEP 2 : Start the dist db server
###############################################################################
#start the dist db server
print_mes STEP2
`eval $rootdir/bin/cubrid server start $dist_db_name > /dev/null`
result=`eval cub_commdb -P | grep $dist_db_name`

if [ -z "$result" ]
then
  $rootdir/bin/cubrid deletedb $dist_db_name
  print_error err_cant_start_dist 
fi

###############################################################################
# STEP 3 : set the password
###############################################################################
#check the DBA password
print_mes STEP3
if [ -n "$passwd" ]
then
  sql="call find_user('DBA') on class db_user to admin;call set_password('$passwd') on admin"
  $rootdir/bin/csql $dist_db_name -u DBA  -c "$sql"  > /dev/null
fi

###############################################################################
# STEP 4 : create tables
###############################################################################
print_mes STEP4
sql="create class db_info (
   dbid   integer PRIMARY KEY,
   dbname varchar(126),
   master_ip varchar(50),
   portnum integer
);
create class master_info as subclass of db_info (
   copylog_path varchar(256) not null,
   start_pageid integer not null,
   first_pageid integer not null,
   last_pageid  integer not null,
   size_of_log_buffer integer default 500 not null,
   size_of_cache_buffer integer default 100 not null,
   size_of_copylog integer default 5000 not null
);

create class trail_info (
   master_dbid integer,
   slave_dbid  integer,
   final_pageid integer,
   final_offset integer,
   all_repl char(1) default 'y' not null,
   repl_count numeric, 
   status char(1) default 'a' not null,
   error_msg string, 
   stop_time timestamp, 
   perf_poll_interval integer default 10, 
   log_apply_interval integer default 0,
   for_recovery char(1) default 'n' not null,
   index_replication char(1) default 'n' not null,
   restart_interval integer default 2,
   PRIMARY KEY(master_dbid, slave_dbid)
);

create class slave_info as subclass of db_info(
   userid       varchar(32),
   passwd       varchar(32),
   trails  set  trail_info
);

create class class_info (
   master_dbid integer,
   class_name varchar(256) not null,
   PRIMARY KEY(master_dbid, class_name)
);

create class delay_info (
   master_dbid integer,
   slave_dbid integer,
   c_time timestamp, 
   delay_time integer,
   PRIMARY KEY(master_dbid, slave_dbid, c_time)
);

create class repl_group (
   master_dbid integer,
   slave_dbid integer,
   class_name varchar(256),
   start_pageid integer,
   start_offset integer,
   PRIMARY KEY(master_dbid, slave_dbid, class_name),
   UNIQUE (slave_dbid, class_name)
);

create class env_info (
   e_name         varchar(32) not null,
   e_value        varchar(256),
   UNIQUE(e_name)
);"

$rootdir/bin/csql $dist_db_name -u DBA -p "$passwd" -c "$sql"

###############################################################################
# STEP 5 : read the master info
###############################################################################
print_mes STEP5
print_mes STEP51
read master_db_name
echo
if [ -z "$master_db_name" ]
then
  print_error err_no_master_name
fi

print_mes STEP52
read master_db_ip
if [ -z "$master_db_ip" ]
then
  print_error err_ip_addr
fi
print_mes STEP53
read port_num
if [ -z "$port_num" ]
then
  print_error err_port_num
fi

echo
print_mes STEP54
read copylog_path
if [ -z "$copylog_path" ]
then
  copylog_path=$CurDir
fi

if [ ! -d $copylog_path ]
then
  print_error err_directory_error
fi

echo
sql="insert into master_info values (1, '$master_db_name', '$master_db_ip', $port_num, '$copylog_path', -1, -1, -1, 500, 100, 5000)"

$rootdir/bin/csql $dist_db_name -u DBA -p "$passwd" -c "$sql"  2> .dist.tmp

result=`eval cat .dist.tmp | grep ERROR`

if [ -n "$result" ]
then
  print_error err_invalid_input
fi

###############################################################################
# STEP 6 : read the environment info
###############################################################################
print_mes STEP6
print_mes STEP61
read trail_log
if [ -z "$trail_log" ]
then
  trail_log=$CurDir
fi
if [ ! -d "$trail_log" ]
then
  print_error err_directory_error
fi
echo
print_mes STEP62
read error_log
if [ -z "$error_log" ]
then
  error_log=$CurDir
fi
if [ ! -d "$error_log" ]
then
  print_error err_directory_error
fi
echo
print_mes STEP63
read agent_port
if [ -z "$agent_port" ]
then
  agent_port=33333
fi
echo
print_mes STEP64
read perf_log_size
if [ -z "$perf_log_size" ]
then
  perf_log_size=10000
fi

sql="insert into env_info values ('trail_log', '$trail_log'); 
     insert into env_info values ('error_log', '$error_log');
     insert into env_info values ('agent_port', '$agent_port');
     insert into env_info values ('perf_log_size', '$perf_log_size');
     insert into env_info values ('commit_interval_msecs', '500');"

$rootdir/bin/csql $dist_db_name -u DBA -p "$passwd" -c "$sql" > /dev/null
