#!/bin/bash

version=$1

if [ -f /etc/os-release ]; then
	. /etc/os-release
	case "${ID}:${VERSION_ID:-${VERSION%% *}}" in
		debian:13|debian:13.*)
			if [ -f /usr/local/zjmf/cloud/apps/upgrade_compute ]; then
				exec /bin/bash /usr/local/zjmf/cloud/apps/upgrade_compute "$version"
			fi
			echo 'Debian 13 upgrade_compute is missing' >&2
			exit 1
			;;
	esac
fi

ctl_ip=`cat /usr/local/zjmf/conf/zjmf.conf |grep "ip=" |awk -F "=" '{print $2}'`

http_server='http://{mirror1.cloud.idcsmart.com,mirror2.cloud.idcsmart.com,mirror.cloud.idcsmart.com}/cloud/compute'
rm -rf /home/zjmf/download/compute/*
mkdir -p /home/zjmf/download/compute
echo "version=$version" > /home/zjmf/download/upgrade.txt
ping -c 1 -w 1 mirror1.cloud.idcsmart.com > /dev/null 2>&1
if [ $? -ne 0 ];then
	ping -c 1 -w 1 mirror2.cloud.idcsmart.com > /dev/null 2>&1
	if [ $? -ne 0 ];then
		ping -c 1 -w 1 mirror.cloud.idcsmart.com > /dev/null 2>&1
		if [ $? -ne 0 ];then
      ping -c 1 -w 1 $ctl_ip > /dev/null 2>&1
      if [ $? -ne 0 ];then
			  echo "stauts=update server and ctl not connected" >> /home/zjmf/download/upgrade.txt
			  exit
			else
			  http_server="https://$ctl_ip:4431/update"
			fi
		fi
	fi
fi
aria2c -x 5 -k 1M --check-certificate=false -c -P ${http_server}/$version.tar.gz -d /home/zjmf/download/compute
supervisorctl stop api-compute
supervisorctl stop ksmtuned
supervisorctl stop api-go
cd /home/zjmf/download/compute
tar xf $version.tar.gz
rm -rf zjmf/conf/*
# 正在运行的 updaemon_compute 以及 aria2c 目标可能是执行中的文件或符号链接。
# 先删除目标再复制，通过新 inode 替换，避免 cp 直接截断时报 Text file busy。
cp -a --remove-destination zjmf/. /usr/local/zjmf/
chmod +x /usr/local/zjmf/cloud/network/*.py
chmod +x /usr/local/zjmf/cloud/*.py
chown -R qemu.qemu /usr/local/zjmf
sleep 1
if [ `lsof -i :4433 |awk '{print $2}' |grep -vi pid |uniq |wc -l` -ne 0 ];then
  for i in `lsof -i :4433 |awk '{print $2}' |grep -vi pid |uniq`;do
    kill -9 $i
  done
fi
sleep 1
supervisorctl start api-compute
supervisorctl start ksmtuned
supervisorctl start api-go

if [ -f "zjmf/update_scripts.sh" ];then
	/bin/bash -x zjmf/update_scripts.sh
fi

echo "status=success" >> /home/zjmf/download/upgrade.txt
rm -rf /home/zjmf/download/compute
