#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
export LC_ALL=C.UTF-8
echo 'DGX Spark 远程接入安装器：将开启 SSH、安装 Tailscale，并设置开机自启。'
echo '请保持电源和网络连接。已有文件和系统密码不会被覆盖。'
die() { printf '\n[未完成 %s] %s\n下一步：%s\n' "$1" "$2" "$3"; exit 1; }
[[ "$(uname -s)" == Linux ]] || die E_OS '请在 DGX Spark 的 Linux 终端执行。' '不要在 Windows 或 Mac 上运行。'
for x in python3 openssl tar sha256sum; do
 command -v "$x" >/dev/null || die E_TOOL "系统缺少 $x。" '拍下这条提示并发回；请勿自行重装系统。'
done
if [[ $EUID -ne 0 ]]; then
 command -v sudo >/dev/null || die E_SUDO '找不到 sudo 管理员工具。' '请使用首次开机时创建的管理员账户。'
 echo '准备：确认管理员权限。请输入这台机器的登录密码，输入时不会显示字符。'
 sudo -v || die E_SUDO '未取得管理员权限，密码可能不正确或此账户不是管理员。' '重新运行，输入本机登录密码。'
fi
TASK_TMP=$(mktemp -d)
trap 'rm -rf "$TASK_TMP"' EXIT
trap 'echo "[已中断] 可以重新执行同一条命令继续。"; exit 130' INT TERM
if [[ -n "${SPARK_CODE_FILE:-}" && -r "$SPARK_CODE_FILE" ]]; then
 cp "$SPARK_CODE_FILE" "$TASK_TMP/code"
else
 echo '准备：请输入 8 位数字安装码（输入时不显示字符）：'
 IFS= read -r -s INSTALL_CODE </dev/tty || die E_CODE '未能读取安装码。' '在有键盘的终端里重新执行。'
 echo
 printf '%s' "$INSTALL_CODE" > "$TASK_TMP/code"
 unset INSTALL_CODE
fi
echo '准备：自动选择下载节点并校验文件；首次约需下载 70 MB。'
python3 - "$TASK_TMP" <<'PY'
import hashlib, http.client, json, math, os, pathlib, shutil, subprocess, sys, tarfile, threading, time, urllib.request, urllib.error
dest = pathlib.Path(sys.argv[1])
manifest = {'config': {'name': 'private-config', 'sha256': '9e4b6927a5fcc2e6f35101f4b112dcaf52c2d863225de6962ac4ac1d2afd30ca'}, 'installer': {'name': 'install.py', 'sha256': 'e20022b38203db0d61ca441782e5717519b28060545c6eb7363beabebb338151'}, 'arm64': {'tailscale': {'name': 'tailscale_1.104.7_arm64.tgz', 'sha256': 'd6bed2720310b328b861f943d7b4016c5358a9bad60575eb51e8143b79068484'}, 'proxy': {'name': 'sing-box-1.14.4-linux-arm64.tar.gz', 'sha256': '436441f76ee2f7fe21b5b2d426d3cb261a480455a704865789ad533e4273ec26'}}, 'amd64': {'tailscale': {'name': 'tailscale_1.104.7_amd64.tgz', 'sha256': 'e56693ff74a64f2591b7e819c280635a100aae1ddfb0ef058fcd052b7cd8d16c'}, 'proxy': {'name': 'sing-box-1.14.4-linux-amd64.tar.gz', 'sha256': '699a1b510aa4396b2176d32d1181920399ebf1e267835da6f3b598d0f7c24968'}}}
mirrors = ['https://spark.sysu-sam.com', 'https://cloud.20020606.xyz/spark-bootstrap', 'http://104.168.255.41:18089', 'https://monitor.43-134-78-71.sslip.io/spark-bootstrap']
arch = {'aarch64': 'arm64', 'arm64': 'arm64', 'x86_64': 'amd64'}.get(os.uname().machine)
def stop(code, text, action):
    print('\n[未完成 '+code+'] '+text+'\n下一步：'+action, flush=True); sys.exit(1)
if arch is None: stop('E_ARCH','不支持此处理器架构。','确认正在 DGX Spark 上运行，并拍照发回。')
# Disable inherited proxy settings: the fallback proxy is installed separately.
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
completed=0
download_deadline=time.monotonic()+900
def size_text(n):
    return f'{n/1024:.1f} KB' if n<1048576 else f'{n/1048576:.1f} MB'
def fetch(item):
    global completed
    name, expected = item['name'], item['sha256']
    label=('Tailscale 安装包' if name.startswith('tailscale_') else '备用代理安装包' if name.startswith('sing-box') else '私有部署配置' if name.endswith('.enc') else '系统配置程序')
    print('\n[下载 '+str(completed+1)+'/4] '+label+'（'+name+'）',flush=True)
    for node_index, base, attempt in [(i,b,a) for i,b in enumerate(mirrors,1) for a in (1,2)]:
        if time.monotonic()>download_deadline:
            stop('E_DOWNLOAD_TIMEOUT','下载已尝试 15 分钟，仍未完成。','确认网络是否需要网页登录；把屏幕提示发回，之后可以重新运行。')
        if attempt==2:
            print('  等待 2 秒后重试当前节点；再次失败才切换。',flush=True);time.sleep(2)
        host=urllib.request.urlparse(base).hostname if hasattr(urllib.request,'urlparse') else base.split('/')[2]
        print('连接节点 '+str(node_index)+'/'+str(len(mirrors))+'：'+host+'，尝试 '+str(attempt)+'/2；连接最多等待 15 秒。', flush=True)
        target=dest/name
        progress={'bytes':0,'total':0,'last':time.monotonic(),'connected':False}
        started=time.monotonic()
        finished=threading.Event()
        def show_progress():
            while not finished.wait(3):
                elapsed=max(time.monotonic()-started,0.001)
                got,total=progress['bytes'],progress['total']
                speed=got/elapsed
                if not progress['connected']:
                    print('  正在建立连接，已等待 '+str(int(elapsed))+' 秒……',flush=True);continue
                size=f'{got/1048576:.1f} MB'
                if total:
                    pct=min(100,int(got*100/total));bar='#'*(pct//5)+'-'*(20-pct//5)
                    size=f'[{bar}] {pct:3d}%  {size} / {total/1048576:.1f} MB'
                rate=f'{speed/1048576:.2f} MB/s' if speed>=1048576 else f'{speed/1024:.0f} KB/s'
                eta=f'，预计还需 {math.ceil((total-got)/speed)} 秒' if total and speed else ''
                waiting=time.monotonic()-progress['last']
                if waiting>=5:eta+='，正在等待网络数据（'+str(int(waiting))+'秒）'
                print('  '+size+'，'+rate+eta,flush=True)
        ticker=threading.Thread(target=show_progress,daemon=True);ticker.start()
        try:
            req=urllib.request.Request(base+'/'+name,headers={'User-Agent':'SparkBootstrap/1'})
            with opener.open(req,timeout=15) as response, target.open('wb') as out:
                progress['connected']=True
                progress['total']=int(response.headers.get('Content-Length','0'))
                print('  已连接，文件大小 '+(size_text(progress['total']) if progress['total'] else '由服务器动态提供')+'，开始下载。',flush=True)
                h=hashlib.sha256()
                while True:
                    chunk=response.read(64*1024)
                    if not chunk: break
                    out.write(chunk); h.update(chunk)
                    progress['bytes']+=len(chunk);progress['last']=time.monotonic()
                    if time.monotonic()-started > 240: raise TimeoutError('download deadline')
                    if time.monotonic()>download_deadline: raise TimeoutError('overall deadline')
                    if time.monotonic()-started>30 and progress['bytes']/(time.monotonic()-started)<32768 and node_index<len(mirrors):
                        print('  当前节点持续低于 32 KB/s，尝试其他路径。',flush=True)
                        raise TimeoutError('slow mirror')
            if h.hexdigest()!=expected:
                print('该节点文件校验不符，将重试或更换节点。',flush=True); continue
            finished.set();ticker.join()
            completed+=1
            print(f"  [####################] 100%  {size_text(progress['bytes'])}，耗时 {time.monotonic()-started:.1f} 秒；SHA256 校验通过。",flush=True);return target
        except urllib.error.HTTPError as e:
            print('节点返回 HTTP '+str(e.code)+'，将重试或更换节点。',flush=True)
        except (OSError,ValueError,urllib.error.URLError,http.client.HTTPException) as e:
            if isinstance(e,OSError) and e.errno==28:
                stop('E_DISK','下载过程中磁盘空间已用完。','联系负责人清理空间，勿随意删除系统文件。')
            reason='网络超时或连接失败'
            if 'CERTIFICATE' in str(e): reason='证书校验失败，请留意机器时间'
            if 'Name or service' in str(e) or 'resolve' in str(e): reason='域名解析失败'
            print(reason+'，将重试或更换节点。',flush=True)
        finally:
            finished.set();ticker.join()
    stop('E_DOWNLOAD','所有下载节点均失败（可能未联网、网络需网页登录、DNS错误或证书时间错误）。','确认能打开普通网页；检查日期和时间；把以上提示拍照发回。')
if shutil.disk_usage(dest).free < 500*1024**2: stop('E_DISK','临时目录剩余空间不足 500 MB。','请联系负责人清理磁盘，不要随意删除系统文件。')
print('[下载 1/4] 校验 8 位安装码并获取私有部署配置。',flush=True)
code=(dest/'code').read_text().strip()
(dest/'code').unlink(missing_ok=True)
if len(code)!=8 or not code.isascii() or not code.isdigit():
    stop('E_CODE','安装码应为 8 位数字。','重新执行命令，输入新版说明中的 8 位安装码。')
config=None
for endpoint in ('https://spark.sysu-sam.com/unlock','https://monitor.43-134-78-71.sslip.io/spark-bootstrap/unlock'):
    for attempt in (1,2):
        print('正在校验安装码，节点 '+endpoint.split('/')[2]+'，尝试 '+str(attempt)+'/2（最多等待 15 秒）。',flush=True)
        try:
            req=urllib.request.Request(endpoint,data=json.dumps({'code':code}).encode(),headers={'Content-Type':'application/json'},method='POST')
            with opener.open(req,timeout=15) as response: raw=response.read(65536)
            if hashlib.sha256(raw).hexdigest()!=manifest['config']['sha256']:
                print('配置版本校验不符，正在尝试备用节点。',flush=True);continue
            config=json.loads(raw);(dest/'config.json').write_bytes(raw)
            print('安装码校验通过，私有配置已获取。',flush=True);break
        except urllib.error.HTTPError as e:
            if e.code==403:stop('E_CODE','安装码不正确。','重新执行命令，输入新版说明中的安装码。')
            if e.code==410:stop('E_EXPIRED','本次安装码已超过使用期限。','联系负责人更新安装包。')
            if e.code==429:stop('E_CODE_LIMIT','安装码错误次数过多，已暂时限制尝试。','等待 15 分钟，核对新版安装码后重试。')
            print('校验服务暂不可用，稍后重试或切换节点。',flush=True)
        except (OSError,ValueError,urllib.error.URLError,http.client.HTTPException):
            print('校验连接暂未成功，稍后重试或切换节点。',flush=True)
        if attempt==1:time.sleep(2)
    if config is not None:break
del code
if config is None:stop('E_CODE_NETWORK','安装码校验节点均未连接成功。','确认网络可用后重跑；把提示拍照发回。')
completed=1
if time.time()>config['expires_at']: stop('E_EXPIRED','本次安装包已超过使用期限。','联系负责人更新安装包；无需重装系统。')
fetch(manifest['installer'])
for item in [manifest[arch]['tailscale'],manifest[arch]['proxy']]: fetch(item)
for key in ['tailscale','proxy']:
    archive=dest/manifest[arch][key]['name']
    with tarfile.open(archive,'r:gz') as tf:
        for member in tf.getmembers():
            basename=pathlib.PurePosixPath(member.name).name
            if basename not in ('tailscale','tailscaled','sing-box') or not member.isfile(): continue
            with tf.extractfile(member) as src,(dest/basename).open('wb') as out: shutil.copyfileobj(src,out)
            (dest/basename).chmod(0o700)
print('安装文件已备齐，即将配置系统服务。',flush=True)
PY
if [[ $EUID -eq 0 ]]; then
 python3 "$TASK_TMP/install.py" --assets-dir "$TASK_TMP"
else
 sudo python3 "$TASK_TMP/install.py" --assets-dir "$TASK_TMP"
fi
