#!/bin/bash
#
# @file
# @brief mysql のダミーデータ生成
#
# @note
# - 事前にテーブル生成
#CREATE TABLE user (
# id int(11) NOT NULL AUTO_INCREMENT,
# name varchar(50) DEFAULT NULL,
# age int(11) DEFAULT NULL,
# description text,
# created_at datetime DEFAULT NULL,
# PRIMARY KEY (`id`)
#) ENGINE=InnoDB;
#
# -実行
# time bash mysql_insert_dummy.sh 100
#
# $Revision$

LOOP=${1:-"10"} #ループ回数
DUMMY_FILE="/tmp/dummy.csv"
DATE=`date '+%Y-%m-%d %H:%M:%S'`
MYSQL_USER=root
MYSQL_PASSWD=`cat ~/.mysql-pw`
MYSQL_DB=test

# rand
# @param int min : default 0
# @param int max : default 32767,  max 32767
# @return int    : 
rand()
{
	local min=0
	local max=32767
	if [ $1 ]; then
		min=$1
	fi
	if [ $2 ]; then
		max=$2
	fi
	echo `echo $(( $min + $RANDOM % ( $max - $min ) ))`
}

# rand_str_fast
# @param int len : default 8, max 1000
# @return int    : 
RANDSTRING=`</dev/urandom tr -dc A-Za-z0-9 | head -c 1000` # 1000文字まで作成しておく
rand_str_fast()
{
	local len=8
	if [ $1 ]; then
		len=$1
	fi
	local max=`echo $(( 1000 - $len ))`
	local start=`rand 1 $max`
	local end=`echo $(( $start + $len -1 ))`
	echo `echo -n "$RANDSTRING" | cut -c$start-$end`
}

rm -f $DUMMY_FILE
for i in `eval echo {1..$LOOP}`; do
	name=`rand_str_fast 10`
	desc=`rand_str_fast 50`
	age=`rand 0 999`
	echo "${i},${name},${age},${desc},${DATE}" >> $DUMMY_FILE
done;

mysql -u $MYSQL_USER -p $MYSQL_PASSWD -D $MYSQL_DB -e "load data local infile '$DUMMY_FILE' into table user fields terminated by ',';"

rm -f $DUMMY_FILE

exit 0
