#!/bin/bash

targetVersion=$1
tseAdapterDownloadUrl=$2

# get tse version via php
tseVersionCommand=$(cat <<- 'PHP'
$ini = parse_ini_file('/var/www/html/Resource/config/config.ini', true);
$tseUrl = $ini['TSE']['TseHost'] ?? 'http://localhost:8014';
$versionResp = file_get_contents("$tseUrl/adapterVersion");
$version = json_decode($versionResp, true)['major'] ?? 'null';
echo $version;
PHP
)
tseVersion=`php -r "$tseVersionCommand"`

# exit if no need to update
if [ $tseVersion != 'null' ]; then
  if [ $targetVersion -le $tseVersion ]; then
    echo "无需更新TSE, 当前版本已是目标版本($tseVersion)"
    exit 1
  fi
fi

# get os version via php
osCommand=$(cat <<- 'PHP'
$osVersion = shell_exec('cat /proc/version');
if (strpos($osVersion, 'microsoft') !== false || strpos($osVersion, 'WSL2') !== false) {
  $os = 'windows';
} else {
  $os = 'linux';
}
echo $os;
PHP
)
os=`php -r "$osCommand"`

# download tse adapter
wget -O latest-tse-adapter.jar "$tseAdapterDownloadUrl"

if [ $os == 'windows' ]; then
  echo "当前系统为Windows系统，更新TSE请使用 aaden-cli update-win-tse"
  exit 1
else
  sudo cp -f latest-tse-adapter.jar /var/www/html/TseHost/tse-0.0.2.jar
  sudo service aaden-tse restart
fi

echo "正在等待TSE服务重启"
sleep 5s
echo "还剩10秒"
sleep 5s
echo "还剩5秒"
sleep 5s
echo "开始检查新TSE版本"

tseVersionCommand2=$(cat <<- 'PHP'
$ini = parse_ini_file('/var/www/html/Resource/config/config.ini', true);
$tseUrl = $ini['TSE']['TseHost'] ?? 'http://localhost:8014';
$versionResp = file_get_contents("$tseUrl/adapterVersion");
$version = json_decode($versionResp, true)['major'] ?? 'null';
echo $version;
PHP
)
tseVersion2=`php -r "$tseVersionCommand2"`

if [ $tseVersion2 != 'null' ]; then
  if [ $targetVersion -le $tseVersion2 ]; then
    echo "TSE升级完成，当前版本为($tseVersion2)"
    exit 1
  fi
fi

echo "TSE升级失败，当前版本为($tseVersion2)"
