#!/bin/bash 
mysql=/usr/bin/mysql; ifconfig=/sbin/ifconfig; iface=eth0; mysql_password="root"; mysql_host="localhost"; mysql_user="root"; limit=1; db="smmart_20"; table="tw_user"
debug=1
log=TDM.log
getoptions(){
    while getopts "hi:t:d:p:f:x:u:l:f:" OPTION; do 
        case "$OPTION" in
            h) usage ;;
            f) file=$OPTARG;;
            p) export mysql_password="$OPTARG";;
            x) export mysql_host="$OPTARG";;
            u) export mysql_user="$OPTARG";;
            i) export iface="$OPTARG";;
            p) export file="$OPTARG";;
            d) export db="$OPTARG";;
            t) export table="$OPTARG";;
            l) export limit="$OPTARG";;
        esac
    done
}

usage(){ cat <<EOF
$0 [OPTION]
    -p PASSWD   set mysql password
    -x HOST     set mysql host
    -u USER     set mysql user
    -l LIMIT    limit of results to get/set 
    -i IFACE    network interface to get ip from
    -d DB       database to use
    -t table    table to use
    -f file     file for import users to database
    -h          show this menu
EOF
exit
}

get_mysql_opts(){
    opts=" "
    [[ "${mysql_password}" != "" ]] && opts="${opts} -p${mysql_password}"
    [[ "${mysql_host}" != "" ]] && opts="${opts} -h${mysql_host}"
    [[ "${mysql_user}" != "" ]] && opts="${opts} -u${mysql_user}"
    echo "${opts}"
}

get_ip(){ $ifconfig $iface|awk '/inet addr/ {print substr($2, 6)}' ; }
execute_mysql_query(){ echo $1| $mysql $(get_mysql_opts) -N $db ; }
set_myself_in_database(){ execute_mysql_query "update $table set task_host='$1', task_status=1 where task_status=0 limit $limit"; }
get_from_database(){ execute_mysql_query "select name from $table where task_host='$1' and task_status=1 limit $limit"; }
get_names(){ csv="$(get_from_database ${ip})"; echo $csv | sed "s/ /,/g" >> $ip.csv ; }

ip=$(get_ip)
getoptions "${@}"

main(){
    while [ "1" ]; do
        [[ $file ]] && { for i in `cat $file`; do execute_mysql_query "insert into $table ('name') values ('$i');"; done; }  
        echo "Connecting to $mysql_host with user $mysql_user and limit $limit for ip $ip and password $mysql_password" >&2
        sleep $[$RANDOM % 200 ]; # Sleep for aleatory startup
        for i in `seq 1 4`; do
            for i in `seq 1 20`; do
                rm $ip.csv;
                set_myself_in_database $ip
                get_from_database ${ip}
                get_names
                TwitterDataMiner --destfile DataMiningFromMysql  --get_only_ff --save_file --user_info --external_users $ip.csv --no-auth --enable_mysql $mysql_host,$mysql_user,$mysql_password,$db >&2 # Note: You can delete desfile and save_file 
            done 
            sleep 900 # Sleep 15m foreach 10 users. This way we won't reach the limits
        done
    done
}

{ cd `mktemp -d`; [[ $debug ]] && { [[ $log ]] && main &> $log || main ; } || main &>/dev/null;  } &
