#!/bin/bash

set -e

show_usage="args: [--runmode=,--serve-addr=,--serve-port=,--etcd-addr=,--etcd-port=,--encrypt-key=,--log-dir=,--image-name=]"

#-o或--options选项后面是可接受的短选项，如ab:c::，表示可接受的短选项为-a -b -c，
#其中-a选项不接参数，-b选项后必须接参数，-c选项的参数为可选的
#-l或--long选项后面是可接受的长选项，用逗号分开，冒号的意义同短选项。
#-n选项后接选项解析错误时提示的脚本名字
ARGS=`getopt -o -h --long help,runmode:,serve-addr:,serve-port:,etcd-addr:,etcd-port:,encrypt-key:,out-ip:,log-dir:,image-name: -n "$0" -- "$@"`

if [ $? != 0 ]; then
    exit 1
fi

#将规范化后的命令行参数分配至位置参数（$1,$2,...)
eval set -- "${ARGS}"

while [ -n "$1" ]
do
    case "$1" in
        -h|--help)
            echo "$show_usage"; exit 1 ;;
        --runmode)
            RUNMODE=$2; shift ;;
        --serve-addr)
            SERVE_ADDR=$2; shift ;;
        --serve-port)
            SERVE_PORT=$2; shift ;;
        --etcd-addr)
            ETCD_ADDR=$2; shift ;;
        --etcd-port)
            ETCD_PORT=$2; shift ;;
        --encrypt-key)
            ENCRYPT_KEY=$2; shift ;;
        --image-name)
            IMAGE_NAME=$2; shift ;;
        --log-dir)
            LOG_DIR=$2; shift ;;
        --out-ip)
            OUT_IP=$2; shift ;;
        *) shift ;;
    esac
done

DISCOVERY_TYPE="k8s"

if [ -z $OUT_IP ];then
    echo "out ip must be specified."
fi

if [ -z $SERVE_PORT ];then
    SERVE_PORT=60001
fi

if [ -z $RUNMODE ];then
    RUNMODE="dev"
fi
if [ -z $SERVE_ADDR ];then
    SERVE_ADDR="0.0.0.0"
fi
if [ -z $ETCD_ADDR ];then
    ETCD_ADDR="127.0.0.1"
fi
if [ -z $ETCD_PORT ];then
    ETCD_PORT="2379"
fi
if [ -z $ENCRYPT_KEY ];then
    ENCRYPT_KEY="a95cbb574bdc905f9bf457820f1fa602"
fi
if [ -z $LOG_DIR ];then
    LOG_DIR="logs"
fi

SERVICE_NAME="gd-management-gateway"

if [ -z $IMAGE_NAME ];then
    IMAGE_NAME=$SERVICE_NAME
fi

PROJECT_PATH=$(cd `dirname $0`; pwd)
APP_NAME="${PROJECT_PATH##*/}"
APP_CONF=conf/app.conf


#生成配置文件
sed -e "s/%APP_NAME%/$APP_NAME/g" ${APP_CONF}.in > ${APP_CONF}
sed -i "s/%APP_NAME%/$APP_NAME/g" ${APP_CONF}
sed -i "s/%RUNMODE%/$RUNMODE/g" ${APP_CONF}
sed -i "s/%SERVE_ADDR%/$SERVE_ADDR/g" ${APP_CONF}
sed -i "s/%SERVE_PORT%/$SERVE_PORT/g" ${APP_CONF}
sed -i "s/%ETCD_ADDR%/$ETCD_ADDR/g" ${APP_CONF}
sed -i "s/%ETCD_PORT%/$ETCD_PORT/g" ${APP_CONF}
sed -i "s/%ENCRYPT_KEY%/$ENCRYPT_KEY/g" ${APP_CONF}
sed -i "s/%LOG_DIR%/$LOG_DIR/g" ${APP_CONF}
sed -i "s/%SERVICE_NAME%/$SERVICE_NAME/g" ${APP_CONF}
sed -i "s/%DISCOVERY_TYPE%/$DISCOVERY_TYPE/g" ${APP_CONF}
sed -i "s/%OUT_IP%/$OUT_IP/g" ${APP_CONF}

VERSION=`cat VERSION`
make version=$VERSION

DOCKERFILE=Dockerfile
DOCKERCOMPOSE=docker/compose/docker-compose.yaml
K8SFILE=docker/kubernetes/$SERVICE_NAME.yaml

sed -e "s/%APP_NAME%/$APP_NAME/g" ${DOCKERFILE}.in > ${DOCKERFILE}
sed -i "s/%SERVE_PORT%/$SERVE_PORT/g" ${DOCKERFILE}

sed -e "s/%SERVICE_NAME%/$SERVICE_NAME/g" ${DOCKERCOMPOSE}.in > ${DOCKERCOMPOSE}

sed -e "s/%SERVICE_NAME%/$SERVICE_NAME/g" ${K8SFILE}.in > ${K8SFILE}
sed -i "s/%SERVE_PORT%/$SERVE_PORT/g" ${K8SFILE}
sed -i "s/%RUNMODE%/$RUNMODE/g" ${K8SFILE}

docker build . -t $IMAGE_NAME

