#!/bin/sh
set -eu
umask 077
temp=$(mktemp -d)
trap 'rm -rf "$temp"' EXIT
get(){ curl --fail --show-error --silent --location --proto '=https' --proto-redir '=https' --tlsv1.2 "$1" -o "$2"; }
check(){ if command -v shasum >/dev/null; then echo "$1  $2" | shasum -a 256 -c - >/dev/null; else echo "$1  $2" | sha256sum -c - >/dev/null; fi; }
nodebin=$(command -v node || true)
if [ -z "$nodebin" ] || ! "$nodebin" -e 'process.exit(+process.versions.node.split(".")[0]>=18?0:1)'; then
  case "$(uname -s)/$(uname -m)" in
    Darwin/arm64) platform=darwin-arm64; sum=679ad4966339e4ef4900f57996714864e4211b898825bb840c3086c419fbcef2 ;;
    Darwin/x86_64) platform=darwin-x64; sum=07b13722d558790fca20bb1ecf61bde24b7a4863111f7be77fc57251a407359a ;;
    Linux/x86_64) platform=linux-x64; sum=07c8aafa60644fb81adefa1ee7da860eb1920851ffdc9a37020ab0be47fbc10e ;;
    Linux/aarch64|Linux/arm64) platform=linux-arm64; sum=1d1690e9aba47e887a275abc6d8f7317e571a0700deaef493f768377e99155f5 ;;
    *) echo '需要 Node.js 18 或更高版本。' >&2; exit 2 ;;
  esac
  name="node-v22.22.1-$platform"
  get "https://nodejs.org/dist/v22.22.1/$name.tar.gz" "$temp/node.tgz"
  check "$sum" "$temp/node.tgz"
  tar -xzf "$temp/node.tgz" -C "$temp" "$name/bin/node"
  dir="$HOME/.esun-employee/runtime/$name"; mkdir -p "$dir"
  if [ ! -f "$dir/node" ]; then cp "$temp/$name/bin/node" "$dir/node.tmp.$$"; chmod 700 "$dir/node.tmp.$$"; mv "$dir/node.tmp.$$" "$dir/node"; fi
  cmp "$temp/$name/bin/node" "$dir/node" >/dev/null
  nodebin="$dir/node"
fi
get 'https://esun.cbecbase.com/esun-employee-connect-1.1.2.tgz' "$temp/employee.tgz"
check 'e269276c1256a9e919afe647a3c87850da630a465df5f6a1701a96285846c1b5' "$temp/employee.tgz"
tar -xzf "$temp/employee.tgz" -C "$temp"
"$nodebin" "$temp/package/install.cjs" "$@"
