File size: 10,934 Bytes
632b0a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
#!/usr/bin/env bash
set -euo pipefail

############################################
# Required env vars (Space 设置):
#   Secrets:
#     HF_TOKEN
#     CODE_SERVER_PASSWORD
#     BASIC_AUTH_PASSWORD
#   Variables:
#     CONFIG_DATASET        e.g. "yourname/ubuntu"
#     BASIC_AUTH_USER       e.g. "gally"
#     SYNC_INTERVAL_SECONDS e.g. "300"
#
# Optional:
#     RESET_CLI_CONFIG=1      # if dataset has no .claude/.codex, remove local remnants to force fresh bootstrap
############################################

: "${CONFIG_DATASET:?CONFIG_DATASET is required, e.g. yourname/ubuntu}"
: "${HF_TOKEN:?HF_TOKEN secret is required}"
: "${CODE_SERVER_PASSWORD:?CODE_SERVER_PASSWORD secret is required}"
: "${BASIC_AUTH_USER:?BASIC_AUTH_USER variable is required}"
: "${BASIC_AUTH_PASSWORD:?BASIC_AUTH_PASSWORD secret is required}"
: "${SYNC_INTERVAL_SECONDS:=300}"

# Use venv python (has huggingface_hub installed)
PY="/opt/venv/bin/python"

# Canonical HOME
export HOME="/home/coder"

# npm globals (claude/codex)
export NPM_CONFIG_CACHE="${NPM_CONFIG_CACHE:-$HOME/.npm}"
export NPM_CONFIG_PREFIX="${NPM_CONFIG_PREFIX:-$HOME/.npm-global}"
export PATH="$HOME/.npm-global/bin:$PATH"
mkdir -p "$NPM_CONFIG_CACHE" "$NPM_CONFIG_PREFIX"
chown -R coder:coder "$HOME" || true

# Make interactive shells stable
cat >/etc/profile.d/00-dev-env.sh <<'EOF'
export HOME=/home/coder
export NPM_CONFIG_PREFIX="$HOME/.npm-global"
export PATH="$HOME/.npm-global/bin:$PATH"
EOF
chmod +x /etc/profile.d/00-dev-env.sh

# De-duplicate PATH injection for bash sessions
if ! grep -q 'npm-global/bin' /home/coder/.bashrc 2>/dev/null; then
  cat >>/home/coder/.bashrc <<'EOF'

# >>> dev env: npm global bin (claude/codex) >>>
export HOME=/home/coder
export NPM_CONFIG_PREFIX="$HOME/.npm-global"
case ":$PATH:" in
  *":$HOME/.npm-global/bin:"*) ;;
  *) export PATH="$HOME/.npm-global/bin:$PATH" ;;
esac
# <<< dev env <<<
EOF
fi
chown coder:coder /home/coder/.bashrc 2>/dev/null || true

# ---- HF auth/cache MUST stay OUT of $HOME (you sync entire HOME) ----
# huggingface_hub supports HF_HOME/HF_HUB_CACHE env vars. [8](https://github.com/q09sssisiwjb/Use-vscode-chrome-terminal)
export HF_TOKEN="${HF_TOKEN}"
export HF_HOME="/tmp/hf_home"
export HF_TOKEN_PATH="/tmp/hf_home/token"
export HF_HUB_CACHE="/tmp/hf_home/hub"
export HF_ASSETS_CACHE="/tmp/hf_home/assets"

rm -rf "${HF_HOME}" 2>/dev/null || true
mkdir -p "${HF_HUB_CACHE}" "${HF_ASSETS_CACHE}"
chmod -R 777 "${HF_HOME}" 2>/dev/null || true

echo "[debug] Using PY=${PY}"
"${PY}" -c "import huggingface_hub; print('[debug] huggingface_hub=', huggingface_hub.__version__)"

# ---- Pull dataset snapshot ----
PERSIST="/persist_repo"
mkdir -p "${PERSIST}"

echo "[boot] Pull dataset snapshot -> ${PERSIST}"
"${PY}" /sync_home.py pull --repo "${CONFIG_DATASET}" --dst "${PERSIST}"

# ---- Restore dataset home -> /home/coder (NO delete) ----
# Keeps image-preinstalled dirs from being wiped.
if [ -d "${PERSIST}/home" ]; then
  echo "[boot] Restore ${PERSIST}/home -> ${HOME} (NO delete)"
  "${PY}" /sync_home.py rsync_in --src "${PERSIST}/home" --dst "${HOME}"
else
  echo "[boot] Dataset has no 'home/' yet. Initializing..."
  mkdir -p "${PERSIST}/home"
fi

# Fix ownership after restore
chown -R coder:coder "${HOME}" || true

# ---- Optional: clean bootstrap of .claude/.codex if dataset lacks them ----
# Use if you want to ensure no local remnants remain when dataset does not have these dirs.
if [ "${RESET_CLI_CONFIG:-0}" = "1" ]; then
  if [ ! -d "${PERSIST}/home/.claude" ]; then rm -rf /home/coder/.claude 2>/dev/null || true; fi
  if [ ! -d "${PERSIST}/home/.codex"  ]; then rm -rf /home/coder/.codex  2>/dev/null || true; fi
  if [ ! -f "${PERSIST}/home/.claude.json" ]; then rm -f /home/coder/.claude.json 2>/dev/null || true; fi
fi

# ---- Restore .claude/.codex only if present in dataset snapshot ----
if [ -d "${PERSIST}/home/.claude" ]; then
  echo "[fix] Restore ~/.claude from dataset (authoritative)"
  mkdir -p /home/coder/.claude
  rsync -a --delete "${PERSIST}/home/.claude/" "/home/coder/.claude/"
  chown -R coder:coder /home/coder/.claude || true
else
  echo "[fix] Dataset has no .claude -> skip restore"
fi

if [ -d "${PERSIST}/home/.codex" ]; then
  echo "[fix] Restore ~/.codex from dataset (authoritative)"
  mkdir -p /home/coder/.codex
  rsync -a --delete "${PERSIST}/home/.codex/" "/home/coder/.codex/"
  chown -R coder:coder /home/coder/.codex || true
else
  echo "[fix] Dataset has no .codex -> skip restore"
fi

# ---- Claude onboarding bypass flag (user-scope file) ----
# Many guides suggest setting hasCompletedOnboarding=true as a TOP-LEVEL field in ~/.claude.json. [1](https://help.aliyun.com/zh/model-studio/claude-code-coding-plan)[2](https://github.com/ding113/claude-code-hub/issues/352)[3](https://linux.do/t/topic/1416398)
# This helps avoid onboarding/login/connectivity blockers. It does not replace API auth. [1](https://help.aliyun.com/zh/model-studio/claude-code-coding-plan)[4](https://code.claude.com/docs/en/settings)
if [ ! -f /home/coder/.claude.json ]; then
  cat >/home/coder/.claude.json <<'EOF'
{ "hasCompletedOnboarding": true }
EOF
else
  # Ensure the key exists at top-level (simple merge: if missing, overwrite with minimal file)
  if ! grep -q '"hasCompletedOnboarding"[[:space:]]*:[[:space:]]*true' /home/coder/.claude.json; then
    cat >/home/coder/.claude.json <<'EOF'
{ "hasCompletedOnboarding": true }
EOF
  fi
fi
chown coder:coder /home/coder/.claude.json || true

# ---- Bootstrap minimal skeleton configs if absent ----
# Claude user settings live in ~/.claude/settings.json. [4](https://code.claude.com/docs/en/settings)[1](https://help.aliyun.com/zh/model-studio/claude-code-coding-plan)
mkdir -p /home/coder/.claude
if [ ! -f /home/coder/.claude/settings.json ]; then
  cat >/home/coder/.claude/settings.json <<'EOF'
{
  "$schema": "https://json-schema.org/claude-code-settings.json",
  "env": {
    "ANTHROPIC_BASE_URL": "",
    "ANTHROPIC_AUTH_TOKEN": "",
    "ANTHROPIC_MODEL": ""
  },
  "permissions": {
    "allow": [],
    "deny": []
  }
}
EOF
fi
if [ ! -f /home/coder/.claude/CLAUDE.md ]; then
  cat >/home/coder/.claude/CLAUDE.md <<'EOF'
# Claude Code global instructions (portable)
EOF
fi
chown -R coder:coder /home/coder/.claude || true

# Codex user config lives in ~/.codex/config.toml. [5](https://stackoverflow.com/questions/66496890/vs-code-nopermissions-filesystemerror-error-eacces-permission-denied)[6](https://hugging-face.cn/docs/hub/spaces-storage)
mkdir -p /home/coder/.codex
if [ ! -f /home/coder/.codex/config.toml ]; then
  cat >/home/coder/.codex/config.toml <<'EOF'
# Codex user config (portable baseline)
# User-level configuration lives in ~/.codex/config.toml. [5](https://stackoverflow.com/questions/66496890/vs-code-nopermissions-filesystemerror-error-eacces-permission-denied)[6](https://hugging-face.cn/docs/hub/spaces-storage)
model_provider = "openai"
# model = "gpt-5.2"
# approval_policy = "on-request"
# sandbox_mode = "workspace-write"
EOF
fi
chown -R coder:coder /home/coder/.codex || true

# ---- Root fallback symlinks (so even processes with HOME=/root use coder configs) ----
rm -rf /root/.claude /root/.codex 2>/dev/null || true
ln -sfn /home/coder/.claude /root/.claude
ln -sfn /home/coder/.codex  /root/.codex
ln -sfn /home/coder/.claude.json /root/.claude.json

# ---- Fix codex vendor binary exec bit (Codex spawns this binary) ----
CODEX_BIN="/home/coder/.npm-global/lib/node_modules/@cometix/codex/vendor/x86_64-unknown-linux-musl/codex/codex"
if [ -f "$CODEX_BIN" ]; then
  echo "[fix] chmod +x codex vendor binary: $CODEX_BIN"
  chmod 755 "$CODEX_BIN" || true
  chmod 755 "$(dirname "$CODEX_BIN")" 2>/dev/null || true
fi

# ---- Install wrappers so claude/codex always runnable (exec-bit loss safe) ----
CLAUDE_JS="/home/coder/.npm-global/lib/node_modules/@anthropic-ai/claude-code/cli.js"
CODEX_JS="/home/coder/.npm-global/lib/node_modules/@cometix/codex/bin/codex.js"

cat >/usr/local/bin/claude <<EOF
#!/usr/bin/env bash
exec /usr/bin/node "${CLAUDE_JS}" "\$@"
EOF
chmod 755 /usr/local/bin/claude

cat >/usr/local/bin/codex <<EOF
#!/usr/bin/env bash
exec /usr/bin/node "${CODEX_JS}" "\$@"
EOF
chmod 755 /usr/local/bin/codex

# ---- Nginx basic auth ----
echo "Adding password for user ${BASIC_AUTH_USER}"
htpasswd -bc /etc/nginx/.htpasswd "${BASIC_AUTH_USER}" "${BASIC_AUTH_PASSWORD}"

if [ -f /etc/nginx/templates/nginx.conf.template ]; then
  cp /etc/nginx/templates/nginx.conf.template /etc/nginx/nginx.conf
fi

# ---- code-server dirs ----
USER_DATA_DIR="/home/coder/.local/share/code-server"
EXT_DIR="/home/coder/.local/share/code-server/extensions"
mkdir -p "${USER_DATA_DIR}/User" "${EXT_DIR}"
chown -R coder:coder "${USER_DATA_DIR}" "${EXT_DIR}" || true

# 设置: create baseline ONCE, never overwrite user changes on reboot
# ---- VS Code user settings: create baseline ONCE, never overwrite user changes ----
SETTINGS_JSON="${USER_DATA_DIR}/User/settings.json"
mkdir -p "${USER_DATA_DIR}/User"
chown -R coder:coder "${USER_DATA_DIR}/User" || true

if [ ! -f "${SETTINGS_JSON}" ]; then
  cat > "${SETTINGS_JSON}" <<'EOF'
{
  "terminal.integrated.defaultProfile.linux": "SAFE_BASH",
  "terminal.integrated.profiles.linux": {
    "SAFE_BASH": { "path": "/bin/bash", "args": ["--noprofile", "--norc"] }
  },
  "terminal.integrated.cwd": "/home/coder",
  "terminal.integrated.env.linux": {
    "HOME": "/home/coder",
    "NPM_CONFIG_PREFIX": "/home/coder/.npm-global",
    "PATH": "/home/coder/.npm-global/bin:${env:PATH}"
  },
  "window.restoreWindows": "none"
}
EOF
  chown coder:coder "${SETTINGS_JSON}" || true
else
  echo "[boot] VS Code settings.json exists -> keep user customizations (no overwrite)"
fi

# ---- Start code-server (ignore last opened to avoid /root watcher EACCES) ----
export PASSWORD="${CODE_SERVER_PASSWORD}"
echo "[boot] Start code-server with explicit user-data-dir/extensions-dir"
su -p coder -c "export HOME=/home/coder; export PATH=/home/coder/.npm-global/bin:\$PATH; \
  /usr/bin/code-server \
    --bind-addr 127.0.0.1:8080 \
    --auth password \
    --ignore-last-opened \
    --user-data-dir /home/coder/.local/share/code-server \
    --extensions-dir /home/coder/.local/share/code-server/extensions \
    /home/coder" &
CODE_PID=$!

# ---- Start nginx (public 7860) ----
nginx -g "daemon off;" &
NGINX_PID=$!

# ---- Sync daemon (home -> dataset) ----
"${PY}" /sync_home.py daemon \
  --repo "${CONFIG_DATASET}" \
  --home "${HOME}" \
  --persist "${PERSIST}" \
  --interval "${SYNC_INTERVAL_SECONDS}" &
SYNC_PID=$!

final_sync() {
  echo "[sync] Final sync..."
  "${PY}" /sync_home.py push --repo "${CONFIG_DATASET}" --home "${HOME}" --persist "${PERSIST}" || true
}

shutdown() {
  echo "[signal] termination received"
  final_sync
  kill "${SYNC_PID}" 2>/dev/null || true
  kill "${CODE_PID}" 2>/dev/null || true
  kill "${NGINX_PID}" 2>/dev/null || true
  exit 0
}

trap shutdown SIGTERM SIGINT

wait "${NGINX_PID}"