#!/usr/bin/env bash set -euo pipefail timestamp() { date '+%Y-%m-%d %H:%M:%S' } log() { printf '[%s] %s\n' "$(timestamp)" "$*" } log_err() { printf '[%s] %s\n' "$(timestamp)" "$*" >&2 } SERVICE_NAME="vmess-domain-rotator" RUN_USER="" RUN_GROUP="" RUN_USER_SET="0" RUN_GROUP_SET="0" RUN_HOME="" PEAK_START_HOUR="19" PEAK_END_HOUR="24" PEAK_TZ="Asia/Shanghai" PEAK_INTERVAL="10min" OFFPEAK_INTERVAL="30min" INSTALL_DEPS="1" CONFIG_PATH="" GIT_PUSH_ENABLED="1" GIT_PUSH_REMOTE="origin" GIT_HTTP_USERNAME="git" GIT_HTTP_TOKEN="" GIT_HTTP_TOKEN_FILE="" GIT_USE_CREDENTIAL_STORE="1" GIT_CREDENTIALS_FILE="" usage() { cat <<'EOF' Usage: sudo bash scripts/install_debian.sh [options] Default behavior: - Uses current git repository directory as working directory (in-place mode) - Uses the user executing sudo as service user - Enables git push after runtime-state commits Options: --user Service user (default: current sudo user) --group Service group (default: current sudo user's group) --interval Alias for --offpeak-interval (default: 30min) --peak-start Peak period start hour, 0-23 (default: 19) --peak-end Peak period end hour, 1-24 (default: 24) --peak-tz Peak period timezone (default: Asia/Shanghai) --peak-interval Update interval during peak (default: 10min) --offpeak-interval Update interval during offpeak (default: 30min) --config Config file path (default: /config.server.json) --git-push <0|1> Enable/disable push to remote (default: 1) --git-push-remote Remote name for push (default: origin) --git-http-username Username for HTTPS auth (default: git) --git-http-token HTTPS token for non-interactive push --git-http-token-file Read HTTPS token from file --git-use-credential-store <0|1> Use git credential.helper store (default: 1) --git-credentials-file Custom credentials file for helper store --no-install-deps Skip apt dependency install -h, --help Show help Examples: sudo bash scripts/install_debian.sh sudo bash scripts/install_debian.sh --config /opt/vmess-domain-rotator/config.server.json sudo bash scripts/install_debian.sh --peak-start 18 --peak-end 23 sudo bash scripts/install_debian.sh --peak-interval 5min --offpeak-interval 15min sudo bash scripts/install_debian.sh --git-push 0 EOF } run_as_service_user() { runuser -u "$RUN_USER" -- env HOME="$RUN_HOME" "$@" } # --- H4: validators for inputs that flow into systemd unit files / shell --- # Refuse anything that could break unit syntax or inject directives. validate_ident() { # user/group/service names: POSIX-portable charset only. local label="$1" value="$2" if [[ ! "$value" =~ ^[A-Za-z_][A-Za-z0-9_.-]*$ ]] || [[ ${#value} -gt 64 ]]; then log_err "Error: invalid $label: '$value' (must match [A-Za-z_][A-Za-z0-9_.-]{0,63})" exit 1 fi } validate_path() { # Absolute path; no CR/LF; no characters that have meaning inside # systemd unit-file value parsing or bash ExecStart parsing. # (POSIX paths cannot contain NUL, so we don't need to test for it.) local label="$1" value="$2" if [[ "$value" != /* ]]; then log_err "Error: $label must be an absolute path: '$value'" exit 1 fi if [[ "$value" == *$'\n'* ]] || [[ "$value" == *$'\r'* ]]; then log_err "Error: $label contains a newline/CR byte" exit 1 fi case "$value" in *'"'*|*'%'*|*'$'*|*'`'*|*'\\'*|*';'*|*'|'*|*'&'*|*'<'*|*'>'*|*' '*) log_err "Error: $label contains a forbidden character (one of: space \" % \$ \\\` \\\\ ; | & < >): '$value'" exit 1 ;; esac } validate_interval() { local label="$1" value="$2" if [[ ! "$value" =~ ^[0-9]+(min|m|h)$ ]]; then log_err "Error: $label must look like '30min' / '5m' / '1h', got: '$value'" exit 1 fi } validate_tz() { local value="$1" if [[ ! "$value" =~ ^[A-Za-z0-9_+/.-]+$ ]] || [[ ${#value} -gt 64 ]]; then log_err "Error: invalid --peak-tz: '$value' (must match [A-Za-z0-9_+/.-]{1,64})" exit 1 fi } validate_ident "service name" "$SERVICE_NAME" while [[ $# -gt 0 ]]; do case "$1" in --user) RUN_USER="$2" RUN_USER_SET="1" shift 2 ;; --group) RUN_GROUP="$2" RUN_GROUP_SET="1" shift 2 ;; --interval) OFFPEAK_INTERVAL="$2" shift 2 ;; --peak-start) PEAK_START_HOUR="$2" shift 2 ;; --peak-end) PEAK_END_HOUR="$2" shift 2 ;; --peak-tz) PEAK_TZ="$2" shift 2 ;; --peak-interval) PEAK_INTERVAL="$2" shift 2 ;; --offpeak-interval) OFFPEAK_INTERVAL="$2" shift 2 ;; --config) CONFIG_PATH="$2" shift 2 ;; --git-push) GIT_PUSH_ENABLED="$2" shift 2 ;; --git-push-remote) GIT_PUSH_REMOTE="$2" shift 2 ;; --git-http-username) GIT_HTTP_USERNAME="$2" shift 2 ;; --git-http-token) GIT_HTTP_TOKEN="$2" shift 2 ;; --git-http-token-file) GIT_HTTP_TOKEN_FILE="$2" shift 2 ;; --git-use-credential-store) GIT_USE_CREDENTIAL_STORE="$2" shift 2 ;; --git-credentials-file) GIT_CREDENTIALS_FILE="$2" shift 2 ;; --no-install-deps) INSTALL_DEPS="0" shift ;; -h|--help) usage exit 0 ;; *) log_err "Unknown option: $1" usage exit 1 ;; esac done if [[ "$(id -u)" -ne 0 ]]; then log_err "Please run as root (use sudo)." exit 1 fi if ! command -v runuser >/dev/null 2>&1; then log_err "Error: runuser is required on Debian for configuring service-user git credentials" exit 1 fi SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" if ! git -C "$SOURCE_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then log_err "Error: Current directory is not a git repository." log_err "This script must be run from within a git repository." exit 1 fi APP_DIR="$SOURCE_DIR" if [[ -z "$CONFIG_PATH" ]]; then CONFIG_PATH="${APP_DIR}/config.server.json" elif [[ "$CONFIG_PATH" != /* ]]; then CONFIG_PATH="${APP_DIR}/${CONFIG_PATH}" fi if [[ ! -r "$CONFIG_PATH" ]]; then log_err "Error: config file not found or unreadable: $CONFIG_PATH" exit 1 fi if [[ -n "${SUDO_USER:-}" ]] && [[ "$RUN_USER_SET" != "1" ]]; then RUN_USER="$SUDO_USER" fi if [[ -n "${SUDO_USER:-}" ]] && [[ "$RUN_GROUP_SET" != "1" ]]; then RUN_GROUP="$(id -gn "$SUDO_USER")" fi if [[ -z "$RUN_USER" ]]; then log_err "Error: Could not determine service user. Please run with sudo or specify --user" exit 1 fi if [[ -z "$RUN_GROUP" ]]; then log_err "Error: Could not determine service group. Please run with sudo or specify --group" exit 1 fi validate_ident "service user" "$RUN_USER" validate_ident "service group" "$RUN_GROUP" validate_tz "$PEAK_TZ" validate_path "APP_DIR" "$APP_DIR" validate_path "CONFIG_PATH" "$CONFIG_PATH" if [[ ! "$GIT_PUSH_ENABLED" =~ ^[01]$ ]]; then log_err "Error: --git-push must be 0 or 1" exit 1 fi if [[ ! "$GIT_USE_CREDENTIAL_STORE" =~ ^[01]$ ]]; then log_err "Error: --git-use-credential-store must be 0 or 1" exit 1 fi if [[ -z "$GIT_PUSH_REMOTE" ]]; then log_err "Error: --git-push-remote cannot be empty" exit 1 fi if [[ -n "$GIT_HTTP_TOKEN" ]] && [[ -n "$GIT_HTTP_TOKEN_FILE" ]]; then log_err "Error: provide either --git-http-token or --git-http-token-file, not both" exit 1 fi if [[ -n "$GIT_HTTP_TOKEN_FILE" ]] && [[ ! -r "$GIT_HTTP_TOKEN_FILE" ]]; then log_err "Error: cannot read token file: $GIT_HTTP_TOKEN_FILE" exit 1 fi if [[ -n "$GIT_HTTP_TOKEN_FILE" ]]; then GIT_HTTP_TOKEN="$(tr -d '\r\n' < "$GIT_HTTP_TOKEN_FILE")" fi if [[ -n "$GIT_HTTP_TOKEN" ]] && [[ -z "$GIT_HTTP_USERNAME" ]]; then log_err "Error: --git-http-username cannot be empty when token is set" exit 1 fi if [[ -n "$GIT_HTTP_TOKEN" ]] && [[ "$RUN_USER" == "root" ]]; then log_err "Error: refusing to store git token for root service user" log_err "Use --user or disable push with --git-push 0" exit 1 fi RUN_HOME="$(getent passwd "$RUN_USER" | cut -d: -f6)" if [[ -z "$RUN_HOME" ]]; then log_err "Error: could not determine home directory for user: $RUN_USER" exit 1 fi to_minutes() { local val="$1" if [[ "$val" =~ ^([0-9]+)min$ ]] || [[ "$val" =~ ^([0-9]+)m$ ]]; then echo "${BASH_REMATCH[1]}" elif [[ "$val" =~ ^([0-9]+)h$ ]]; then echo $(( ${BASH_REMATCH[1]} * 60 )) elif [[ "$val" =~ ^[0-9]+$ ]]; then echo "$val" else echo "" fi } validate_interval "--peak-interval" "$PEAK_INTERVAL" validate_interval "--offpeak-interval" "$OFFPEAK_INTERVAL" PEAK_INTERVAL_MIN=$(to_minutes "$PEAK_INTERVAL") OFFPEAK_INTERVAL_MIN=$(to_minutes "$OFFPEAK_INTERVAL") if [[ -z "$PEAK_INTERVAL_MIN" ]] || [[ "$PEAK_INTERVAL_MIN" -eq 0 ]]; then log_err "Error: invalid peak interval: $PEAK_INTERVAL" exit 1 fi if [[ -z "$OFFPEAK_INTERVAL_MIN" ]] || [[ "$OFFPEAK_INTERVAL_MIN" -eq 0 ]]; then log_err "Error: invalid offpeak interval: $OFFPEAK_INTERVAL" exit 1 fi # Timer runs at the minimum of the two intervals to handle both schedules if [[ "$PEAK_INTERVAL_MIN" -lt "$OFFPEAK_INTERVAL_MIN" ]]; then TIMER_INTERVAL="$PEAK_INTERVAL" else TIMER_INTERVAL="$OFFPEAK_INTERVAL" fi if [[ "$INSTALL_DEPS" == "1" ]]; then export DEBIAN_FRONTEND=noninteractive apt-get update -y apt-get install -y python3 ca-certificates git fi RUNTIME_DIR="$(/usr/bin/python3 "${APP_DIR}/scripts/domain_updater.py" --config "$CONFIG_PATH" --print-output-settings | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin)["runtime_dir"])')" validate_path "RUNTIME_DIR" "$RUNTIME_DIR" mkdir -p "$RUNTIME_DIR" chmod +x "$APP_DIR/scripts/run_update_and_commit.sh" || true chown -R "$RUN_USER:$RUN_GROUP" "$RUNTIME_DIR" SERVICE_STATE_DIR="/var/lib/${SERVICE_NAME}" ENV_FILE="/etc/${SERVICE_NAME}.env" TOKEN_FILE="" REMOTE_URL="" AUTH_MODE="header" if [[ "$GIT_USE_CREDENTIAL_STORE" == "1" ]]; then AUTH_MODE="credential-helper-store" fi mkdir -p "$SERVICE_STATE_DIR" chown "$RUN_USER:$RUN_GROUP" "$SERVICE_STATE_DIR" chmod 750 "$SERVICE_STATE_DIR" if [[ "$GIT_PUSH_ENABLED" == "1" ]]; then REMOTE_URL="$(git -C "$APP_DIR" remote get-url "$GIT_PUSH_REMOTE" 2>/dev/null || true)" if [[ -z "$REMOTE_URL" ]]; then log_err "Warning: remote '$GIT_PUSH_REMOTE' not found now. Push may fail until remote is configured." fi fi if [[ -n "$GIT_HTTP_TOKEN" ]]; then if [[ "$GIT_USE_CREDENTIAL_STORE" == "1" ]]; then if [[ "$REMOTE_URL" =~ ^https:// ]]; then helper_value="store" if [[ -n "$GIT_CREDENTIALS_FILE" ]]; then helper_value="store --file ${GIT_CREDENTIALS_FILE}" mkdir -p "$(dirname "$GIT_CREDENTIALS_FILE")" touch "$GIT_CREDENTIALS_FILE" chown "$RUN_USER:$RUN_GROUP" "$GIT_CREDENTIALS_FILE" chmod 600 "$GIT_CREDENTIALS_FILE" fi run_as_service_user git config --global credential.helper "$helper_value" printf 'url=%s\nusername=%s\npassword=%s\n\n' "$REMOTE_URL" "$GIT_HTTP_USERNAME" "$GIT_HTTP_TOKEN" | run_as_service_user git credential approve else log_err "Warning: token provided but remote is not HTTPS; credential.helper store setup skipped." log_err "Warning: fallback to header-token-file auth mode for this install." GIT_USE_CREDENTIAL_STORE="0" fi fi if [[ "$GIT_USE_CREDENTIAL_STORE" != "1" ]]; then TOKEN_FILE="${SERVICE_STATE_DIR}/git_http_token" printf '%s\n' "$GIT_HTTP_TOKEN" >"$TOKEN_FILE" chown "$RUN_USER:$RUN_GROUP" "$TOKEN_FILE" chmod 600 "$TOKEN_FILE" AUTH_MODE="header-token-file" fi fi run_as_service_user git config --global --add safe.directory "$APP_DIR" || true cat >"$ENV_FILE" <>"$ENV_FILE" else printf 'GIT_CREDENTIAL_HELPER=store\n' >>"$ENV_FILE" fi fi if [[ -n "$TOKEN_FILE" ]]; then printf 'GIT_HTTP_TOKEN_FILE=%s\n' "$TOKEN_FILE" >>"$ENV_FILE" fi chown root:root "$ENV_FILE" chmod 600 "$ENV_FILE" cat >"/etc/systemd/system/${SERVICE_NAME}.service" <"/etc/systemd/system/${SERVICE_NAME}.timer" <