#!/usr/bin/env bash
set -Eeuo pipefail

app_root=/opt/chuang-employee-workspace
expected_instance=i-bp12cxaffzv65fuyd892
payload=/var/tmp/chuang-workspace-guizang-ppt-skill-v0.23.0.tgz
expected_payload_sha=74712277bf5951df2f6a3e7d047c9ef4c33ee962bbe6d03d0f807d40a65e0956
expected_homepage_sha=a3a5466e525b41f4e9b37ab8426813c0fa2d207b1ec6fc0ba041d525d0a1d1de
stamp="$(date -u +%Y%m%d-%H%M%S)-guizang-ppt-skill-v0.23.0"
previous_release="$(readlink -f "$app_root/current")"
new_release="$app_root/releases/$stamp"
runtime_node="$app_root/runtime/bin/node"
switched=0

sha() { sha256sum "$1" | awk '{print $1}'; }
public_sha() { curl --proto '=https' --tlsv1.2 -fsS --max-time 20 "$1" | sha256sum | awk '{print $1}'; }

rollback() {
  set +e
  if [[ "$switched" -eq 1 && -d "$previous_release" ]]; then
    ln -sfn "$previous_release" "$app_root/current.rollback"
    mv -Tf "$app_root/current.rollback" "$app_root/current"
    systemctl restart chuang-employee-workspace.service
  fi
}
trap rollback ERR

[[ "$EUID" -eq 0 ]]
metadata_base=http://100.100.100.200/latest
metadata_token="$(curl -fsS --max-time 3 -X PUT -H 'X-aliyun-ecs-metadata-token-ttl-seconds: 180' "$metadata_base/api/token")"
actual_instance="$(curl -fsS --max-time 3 -H "X-aliyun-ecs-metadata-token: $metadata_token" "$metadata_base/meta-data/instance-id")"
[[ "$actual_instance" == "$expected_instance" ]]
[[ -d "$previous_release" && ! -e "$new_release" ]]
systemctl is-active --quiet chuang-employee-workspace.service
[[ -f "$payload" && "$(sha "$payload")" == "$expected_payload_sha" ]]
[[ "$(public_sha https://sail-crm.chuangchuang.cn/)" == "$expected_homepage_sha" ]]

mkdir -p "$new_release"
cp -a "$previous_release/." "$new_release/"
rm -rf "$new_release/dist"
tar -xzf "$payload" -C "$new_release"

test -f "$new_release/skills/guizang-ppt-skill/SKILL.md"
test -f "$new_release/skills/guizang-ppt-skill/assets/template-swiss.html"
test -f "$new_release/server/vendor/guizang/template-swiss.html"
grep -q 'buildCoursewareGuizangHtml' "$new_release/server/server.mjs"
grep -q '归藏 PPT 技能' "$new_release/dist/assets/"index-*.js
"$runtime_node" --check "$new_release/server/server.mjs"

chown -R chuang-workspace:chuang-workspace "$new_release"
runuser -u chuang-workspace -- env RELEASE_ROOT="$new_release" "$runtime_node" --input-type=module - <<'NODE'
const root = process.env.RELEASE_ROOT;
const { buildCoursewarePptx, buildCoursewareGuizangHtml, buildSpeakerNotes } = await import(`file://${root}/server/lib/courseware.mjs`);
const spec = {
  title: "归藏技能云端验收",
  subtitle: "员工工作台课件能力",
  author: "创创",
  slides: [
    { title: "课程目标", layoutType: "cover", body: ["形成可下载的静态课件"] },
    { title: "交付内容", layoutType: "statement", body: ["PowerPoint", "网页 PPT", "讲师稿"] },
  ],
};
const [pptx, html, notes] = await Promise.all([
  buildCoursewarePptx(spec),
  buildCoursewareGuizangHtml(spec),
  Promise.resolve(buildSpeakerNotes(spec)),
]);
if (pptx.subarray(0, 2).toString("ascii") !== "PK") throw new Error("pptx invalid");
if (!html.toString("utf8").includes('data-layout="S01"')) throw new Error("guizang html invalid");
if (!notes.toString("utf8").includes("课程目标")) throw new Error("notes invalid");
NODE
chown -R root:root "$new_release"
chmod -R u=rwX,go=rX "$new_release"

ln -sfn "$new_release" "$app_root/current.next"
mv -Tf "$app_root/current.next" "$app_root/current"
switched=1
systemctl restart chuang-employee-workspace.service

for _ in $(seq 1 30); do
  if curl -fsS --max-time 4 http://127.0.0.1:4311/workspace-api/healthz | grep -q '"status":"ready"'; then
    break
  fi
  sleep 1
done
systemctl is-active --quiet chuang-employee-workspace.service
curl -fsS --max-time 8 http://127.0.0.1:4311/workspace-api/healthz | grep -q '"status":"ready"'
curl --proto '=https' --tlsv1.2 -fsS --max-time 15 https://sail-crm.chuangchuang.cn/workspace-api/healthz | grep -q '"status":"ready"'
public_index="$(curl --proto '=https' --tlsv1.2 -fsS --max-time 15 https://sail-crm.chuangchuang.cn/workspace/)"
public_asset="$(printf '%s' "$public_index" | grep -oE 'assets/index-[A-Za-z0-9_-]+\.js' | head -1)"
[[ -n "$public_asset" ]]
curl --proto '=https' --tlsv1.2 -fsS --max-time 20 "https://sail-crm.chuangchuang.cn/workspace/$public_asset" | grep -q '归藏 PPT 技能'
[[ "$(public_sha https://sail-crm.chuangchuang.cn/)" == "$expected_homepage_sha" ]]

rm -f "$payload"
switched=0
trap - ERR
printf 'RELEASE=%s\n' "$new_release"
printf 'ROLLBACK_RELEASE=%s\n' "$previous_release"
printf 'INSTANCE=%s\n' "$actual_instance"
printf 'GUIZANG_PPT_SKILL_DEPLOY_OK\n'
