#!/bin/bash

declare access_key=""
declare secret_access_key=""
declare ip_address=""
declare sql_file="tpcds_load_data_from_obs.sql"
declare sql_bak="tpcds_load_data_from_obs.sql.template"

function print_help()
{
    echo "Usage: $0 [OPTION]
    -h|--help        show help information
    -ak              provide the access_key of the OBS bucket, will replace the access_key of DDL statment of tpcds_load_data_from_obs.sql
    -sk              provide the secret_access_key of the OBS bucket, will replace the secret_access_key of DDL statment of tpcds_load_data_from_obs.sql
    -obs_location    provide the location of the OBS bucket, can be IP address or domain name, will replace the location of DDL statment of tpcds_ddl_create_obs_table.sql
        "
}


if [ $# = 0 ] ; then 
    echo "missing option"
    print_help 
    exit 1
fi


while [ $# -gt 0 ]; do   
    case $1 in   
        -h|--help)   
            print_help   
            exit 1  
            ;;   
        -ak)   
            if [ "$2"X = X ];then
                echo "no given access_key"
                exit 1
            fi
            access_key=$2  
            shift 2  
            ;;   
        -sk)   
            if [ "$2"X = X ];then
                echo "no given secret_access_key"
                exit 1
            fi
            secret_access_key=$2  
            shift 2  
            ;;  
        -obs_location)
            if [ "$2"X = X ];then
                echo "no given obs_location"
                exit 1
            fi
            obs_location=$2
            shift 2
            ;;
        *)
            echo "Internal Error: option processing error: $1" 1>&2  
            echo "please input right paramtenter, the following command may help you"
            echo "./setup.sh --help or ./setup.sh -h"
            exit 1  
    esac   

done 

if [ "$access_key"X = X ];then
    echo "please input access_key with the -ak option"
    exit 1  
fi

if [ "$secret_access_key"X = X ];then
    echo "please input secret_access_key with the -sk option"
    exit 1  
fi

if [ "$obs_location"X = X ];then
    echo "please input obs_location with the -obs_location option"
    exit 1  
fi
if [ ! -f $sql_file ];then
    echo "the $sql_file does not exists"
    exit 1
fi

echo "==========================================="
echo "access_key        : ["******"]"
echo "secret_access_key : ["******"]"
echo "obs_location      : ["$obs_location"]"
echo "sql_file          : ["$sql_file"]"
echo "==========================================="

if [ -f $sql_bak ];then
    cp -f $sql_bak $sql_file
else
    cp -f $sql_file $sql_bak
fi 

sed -i "s/secret_access_key_value_to_be_replaced/${secret_access_key}/g" ${sql_file}
sed -i "s/access_key_value_to_be_replaced/${access_key}/g" ${sql_file}
sed -i "s/xxx.xxx.xxx.xxx/${obs_location}/g" $sql_file


echo "setup successfully!"

