#!/bin/sh

echo -e "\033[36m[INFO] Get local IP ...\033[0m"
LOCAL_IP=
host_ips=(`ip addr show | grep inet | grep -v inet6 | grep brd | awk '{print $2}' | cut -f1 -d '/'`)
if [ "$host_ips" == "" ]; then
  echo -e "\033[31m[ERROR] Get host ip address error\033[0m"
  exit 1
fi
host_ip=
for i in ${host_ips[@]}
do
  ip_parts=(${i//./ })
  if [ ${ip_parts[0]} -eq 10 ]; then
    host_ip=$i
    break
  fi
  if [ ${ip_parts[0]} -eq 172 ] && [ ${ip_parts[1]} -ge 16 ]; then
    host_ip=$i
    break
  fi
  if [ ${ip_parts[0]} -eq 192 ] && [ ${ip_parts[1]} -eq 168 ]; then
    host_ip=$i
    break
  fi
done
if [ "$host_ip" == "" ]; then
  host_ip=${host_ips[0]}
fi
LOCAL_IP=$host_ip
echo -e "\033[36m[INFO] Local IP address: $LOCAL_IP\033[0m"
if [ -z "$LOCAL_IP" ]; then
        echo -e "\033[31m[ERROR] LOCAL_IP must be set, we cannot get this parameter from your linux system.\033[0m"
        exit 1;
fi
echo -e "\033[36m[INFO] Get public IP ...\033[0m"
public_ip=`curl http://metadata.tencentyun.com/meta-data/public-ipv4 | head -1`
if [ -z "$public_ip" ]; then
  public_ip=$LOCAL_IP
fi
echo -e "\033[36m[INFO] Public IP address: $public_ip\033[0m"

echo -e "\033[36m[INFO] Get node hostname ...\033[0m"
node_hostname=$(hostname)
hostname_cnt=`echo $node_hostname | sed -r 's/[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*//g'`
hostname_length=`echo $node_hostname | wc -L`
if [ -n "$hostname_cnt" -o $hostname_length -ge 64 ]; then
  node_hostname=`echo $LOCAL_IP | awk -F '.' '{print "node-"$3"-"$4}'`
fi
echo -e "\033[32m[OK] Node hostname is: $node_hostname\033[0m"

echo -e "\033[36m[INFO] Update /etc/hosts file ...\033[0m"
echo "$LOCAL_IP $node_hostname" >> /etc/hosts

echo -e "\033[36m[INFO] Update /etc/resolv.conf file ...\033[0m"
chattr -i /etc/resolv.conf
sed -i '1i\search default.svc.domeos.local svc.domeos.local domeos.local' /etc/resolv.conf
chattr +i /etc/resolv.conf

echo -e "\033[36m[INFO] Set docker registry configuration ...\033[0m"
sed -i "s/localhost/$LOCAL_IP/g" /etc/sysconfig/docker
systemctl restart docker
sleep 3

echo -e "\033[36m[INFO] Start redis ...\033[0m"
docker run -d --name domeos_redis --restart=always -p 6379:6379 pub.domeos.org/domeos/redis:3.0.7 redis-server --timeout 300 --maxmemory 5gb --maxmemory-policy allkeys-lru --port 6379

echo -e "\033[36m[INFO] Start registry ...\033[0m"
docker run -d --name domeos_registry --restart=always -d -p 5000:5000 -e REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY=/var/lib/registry -v /data/domeos/registry:/var/lib/registry pub.domeos.org/domeos/registry:2.5.1-enhanced

echo -e "\033[36m[INFO] Start mysql ...\033[0m"
docker run --name=domeos_mysql -p 3306:3306 --restart=always -v /data/domeos/mysql:/var/lib/mysql -e MYSQL_USER=domeos -e MYSQL_PASSWORD=domeos-mysql-pw -e MYSQL_ROOT_PASSWORD=root-mysql-pw -e LOCAL_IP=$LOCAL_IP -e DOMEOS_PREFIX=domeos -e KUBE_PORT=8888 -e DOMEOS_PORT=8080 -d pub.domeos.org/domeos/mysql-domeos:5.8-cloud
sleep 5

echo -e "\033[36m[INFO] Start monitor ...\033[0m"
docker run -d --name domeos_graph --restart=always -p 6071:6071 -p 6070:6070 -v /data/domeos/graph/data:/home/work/data/6070 -e DB_DSN="\"domeos:domeos-mysql-pw@tcp($LOCAL_IP:3306)/graph?loc=Local&parseTime=true\"" pub.domeos.org/domeos/graph:0.5.7-supervisor

docker run -d --name domeos_transfer --restart=always -p 6060:6060 -p 8433:8433 -e JUDGE_CLUSTER="\"judge-00\" : \"$LOCAL_IP:6080\"" -e GRAPH_CLUSTER="\"graph-00\" : \"$LOCAL_IP:6070\"" pub.domeos.org/domeos/transfer:0.0.15-supervisor

docker run -d --name domeos_hbs --restart=always -p 6031:6031 -p 6030:6030 -e DATABASE="\"domeos:domeos-mysql-pw@tcp($LOCAL_IP:3306)/portal?loc=Local&parseTime=true\"" pub.domeos.org/domeos/hbs:1.1.0-supervisor

docker run -d --name domeos_query --restart=always -p 9966:9966 -e GRAPH_CLUSTER="\"graph-00\" : \"$LOCAL_IP:6070\"" pub.domeos.org/domeos/query:1.5.1-supervisor

docker run -d --name domeos_judge --restart=always -p 6081:6081 -p 6080:6080 -e HBS_SERVERS="[\"$LOCAL_IP:6030\"]" -e ALARM_REDIS_DSN="\"$LOCAL_IP:6379\"" pub.domeos.org/domeos/judge:2.0.2-supervisor

docker run -d --name domeos_alarm --restart=always -p 9912:9912 -e DATABASE="\"domeos:domeos-mysql-pw@tcp($LOCAL_IP:3306)/domeos?loc=Local&parseTime=true\"" -e REDIS_ADDR="\"$LOCAL_IP:6379\"" -e API_DOMEOS="\"$LOCAL_IP:8080\"" pub.domeos.org/domeos/alarm:1.0-supervisor

docker run -d --name domeos_sender --restart=always -p 6066:6066 -e DATABASE="\"domeos:domeos-mysql-pw@tcp($LOCAL_IP:3306)/domeos?loc=Local&parseTime=true\"" -e REDIS_ADDR="\"$LOCAL_IP:6379\"" pub.domeos.org/domeos/sender:1.0-supervisor

docker run -d --name domeos_nodata --restart=always -p 6090:6090 -e QUERY_QUERYADDR="\"$LOCAL_IP:9966\"" -e CONFIG_DSN="\"domeos:domeos-mysql-pw@tcp($LOCAL_IP:3306)/portal?loc=Local&parseTime=true\"" -e SENDER_TRANSFERADDR="\"$LOCAL_IP:6060\"" pub.domeos.org/domeos/nodata:0.0.8-supervisor

docker run -d --restart=always -p 2222:2222 -e IP="\"$LOCAL_IP\"" -e HOSTNAME="\"$node_hostname\"" -e TRANSFER_ADDR="[\"$LOCAL_IP:8433\"]" -e TRANSFER_INTERVAL="10" -e HEARTBEAT_ENABLED="true" -e HEARTBEAT_ADDR="\"$LOCAL_IP:6030\"" -v /:/rootfs:ro -v /var/run/docker.sock:/var/run/docker.sock --name agent pub.domeos.org/domeos/agent:2.6-supervisor

echo -e "\033[36m[INFO] Start webssh ...\033[0m"
docker run -d --name domeos_shellinabox --restart=always -p 4200:4200 pub.domeos.org/domeos/shellinabox:1.1

echo -e "\033[36m[INFO] Start etcd ...\033[0m"
sed -i "s/localhost/$LOCAL_IP/g" /etc/sysconfig/etcd
systemctl restart etcd
systemctl status -l etcd
systemctl enable etcd
sleep 3

echo -e "\033[36m[INFO] Start flannel ...\033[0m"
FLANNEL_PREFIX="/flannel/network"
flannel_network_ip_range='172.24.0.0/13'
flannel_subnet_len=22
flannel_k8s_config="{\"Network\": \"${flannel_network_ip_range}\", \"SubnetLen\": ${flannel_subnet_len}, \"Backend\": {\"Type\": \"vxlan\", \"VNI\": 1}}"
single_etcd_server="http://$LOCAL_IP:2379"
curl -L $single_etcd_server/v2/keys$FLANNEL_PREFIX/config -XPUT -d value="${flannel_k8s_config}"
systemctl disable flanneld
systemctl restart flanneld
systemctl status flanneld
systemctl enable flanneld

echo -e "\033[36m[INFO] Start master ...\033[0m"
sed -i "s/localhost/$LOCAL_IP/g" /etc/sysconfig/kube-controller
sed -i "s/localhost/$LOCAL_IP/g" /etc/sysconfig/kube-scheduler
systemctl restart kube-apiserver kube-controller kube-scheduler kube-proxy
systemctl status -l kube-apiserver kube-controller kube-scheduler kube-proxy
systemctl enable kube-apiserver kube-controller kube-scheduler kube-proxy
sleep 3

echo -e "\033[36m[INFO] Start node ...\033[0m"
sed -i "s/node-domeos/$node_hostname/g" /etc/sysconfig/kubelet
systemctl restart kubelet
systemctl status kubelet
systemctl enable kubelet
sleep 3

echo -e "\033[36m[INFO] Create dns ...\033[0m"
echo -e "\033[36m[INFO] Get local nameserver ...\033[0m"
ns='8.8.8.8:53'
ns_count=`cat /etc/resolv.conf | grep 'nameserver' | wc -l`
if [ $ns_count -gt 0 ]; then
  ns=`cat /etc/resolv.conf | grep 'nameserver' | awk '{printf $2":53,"}' | sed 's/,$//'`
fi
cat >> dns.yaml <<EOF
apiVersion: v1
kind: Service
metadata:
  name: skydns-svc
  labels:
    app: skydns-svc
spec:
  selector:
    app: skydns
  type: ClusterIP
  clusterIP: 172.16.40.1
  ports:
    - name: dns
      port: 53
      protocol: UDP
    - name: dns-tcp
      port: 53
      protocol: TCP
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: skydns
  labels:
    app: skydns
    version: v9
spec:
  replicas: 1
  selector:
    matchLabels:
      app: skydns
      version: v9
  template:
    metadata:
      labels:
        app: skydns
        version: v9
    spec:
      containers:
        - name: skydns
          image: pub.domeos.org/domeos/skydns:1.5
          command:
            - "/skydns"
          args:
            - "--machines=http://$LOCAL_IP:2379"
            - "--domain=domeos.local"
            - "--addr=0.0.0.0:53"
            - "--nameservers=$ns"
          ports:
            - containerPort: 53
              name: dns-udp
              protocol: UDP
            - containerPort: 53
              name: dns-tcp
              protocol: TCP
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: kube2sky
  labels:
    app: kube2sky
    version: v9
spec:
  replicas: 1
  selector:
    matchLabels:
      app: kube2sky
      version: v9
  template:
    metadata:
      labels:
        app: kube2sky
        version: v9
    spec:
      containers:
        - name: kube2sky
          image: pub.domeos.org/domeos/kube2sky:0.7
          command:
            - "/kube2sky"
          args:
            - "--etcd_servers=http://$LOCAL_IP:2379"
            - "--domain=domeos.local"
            - "--kube_master_url=http://$LOCAL_IP:8888"
EOF
/usr/sbin/domeos/k8s/current/kubectl -s localhost:8888 create -f dns.yaml

echo -e "\033[36m[INFO] Set node label ...\033[0m"
/usr/sbin/domeos/k8s/current/kubectl -s localhost:8888 label nodes $node_hostname --overwrite TESTENV=HOSTENVTYPE PRODENV=HOSTENVTYPE BUILDENV=HOSTENVTYPE
sleep 3

echo -e "\033[36m[INFO] Start domeos server ...\033[0m"
docker run -d --name=domeos_server --restart=always -p 8080:8080 -e MYSQL_HOST=$LOCAL_IP -e MYSQL_PORT=3306 -e MYSQL_USERNAME=domeos -e MYSQL_PASSWORD=domeos-mysql-pw -e MYSQL_DB=domeos -e SHIRO_REDIS_HOST=$LOCAL_IP -e SHIRO_REDIS_PORT=6379 pub.domeos.org/domeos/server:1.6.0-cloud

echo -e "\033[36m[INFO] Waiting for server to start success ...\033[0m"
timeout=0
while true; do
  if [ $timeout -ge 10 ]; then
    echo -e "\033[31m[ERROR] Server(http://${public_ip}:8080) startup timeout(30s)\033[0m"
    exit 1
  fi
  curl -s http://${public_ip}:8080
  _r="$?"
  if [ "$_r" == "0" ]; then
    break
  fi
  let timeout++
  echo "Attempt to connect to server $timeout times ..."
  sleep 3
done
echo -e "\033[32m[OK] DomeOS start successfully, please use browser to visit http://${public_ip}:8080\033[0m"
