| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501 |
- #!/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 <name> Service user (default: current sudo user)
- --group <name> Service group (default: current sudo user's group)
- --interval <value> Alias for --offpeak-interval (default: 30min)
- --peak-start <hour> Peak period start hour, 0-23 (default: 19)
- --peak-end <hour> Peak period end hour, 1-24 (default: 24)
- --peak-tz <timezone> Peak period timezone (default: Asia/Shanghai)
- --peak-interval <value> Update interval during peak (default: 10min)
- --offpeak-interval <value> Update interval during offpeak (default: 30min)
- --config <path> Config file path (default: <repo>/config.server.json)
- --git-push <0|1> Enable/disable push to remote (default: 1)
- --git-push-remote <name> Remote name for push (default: origin)
- --git-http-username <u> Username for HTTPS auth (default: git)
- --git-http-token <t> HTTPS token for non-interactive push
- --git-http-token-file <f> Read HTTPS token from file
- --git-use-credential-store <0|1> Use git credential.helper store (default: 1)
- --git-credentials-file <f> 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 <non-root> 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" <<EOF
- GIT_PUSH_ENABLED=${GIT_PUSH_ENABLED}
- GIT_PUSH_REQUIRED=${GIT_PUSH_ENABLED}
- GIT_PUSH_REMOTE=${GIT_PUSH_REMOTE}
- GIT_RUNTIME_BRANCH=runtime-state
- GIT_HTTP_USERNAME=${GIT_HTTP_USERNAME}
- HOME=${RUN_HOME}
- PEAK_START_HOUR=${PEAK_START_HOUR}
- PEAK_END_HOUR=${PEAK_END_HOUR}
- PEAK_TZ=${PEAK_TZ}
- PEAK_INTERVAL_MIN=${PEAK_INTERVAL_MIN}
- OFFPEAK_INTERVAL_MIN=${OFFPEAK_INTERVAL_MIN}
- EOF
- if [[ "$GIT_USE_CREDENTIAL_STORE" == "1" ]]; then
- if [[ -n "$GIT_CREDENTIALS_FILE" ]]; then
- printf 'GIT_CREDENTIAL_HELPER=store --file %s\n' "$GIT_CREDENTIALS_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" <<EOF
- [Unit]
- Description=VMess Domain Rotator updater
- After=network-online.target
- Wants=network-online.target
- [Service]
- Type=oneshot
- User=${RUN_USER}
- Group=${RUN_GROUP}
- WorkingDirectory="${APP_DIR}"
- EnvironmentFile=-${ENV_FILE}
- UMask=0077
- ExecStart=/bin/bash "${APP_DIR}/scripts/run_update_and_commit.sh" "${CONFIG_PATH}"
- EOF
- cat >"/etc/systemd/system/${SERVICE_NAME}.timer" <<EOF
- [Unit]
- Description=Run VMess Domain Rotator every ${TIMER_INTERVAL}
- [Timer]
- OnBootSec=2min
- OnUnitActiveSec=${TIMER_INTERVAL}
- AccuracySec=30s
- Unit=${SERVICE_NAME}.service
- Persistent=true
- [Install]
- WantedBy=timers.target
- EOF
- systemctl daemon-reload
- systemctl enable --now "${SERVICE_NAME}.timer"
- systemctl start "${SERVICE_NAME}.service"
- log ""
- log "✓ Installation complete!"
- log ""
- log "Configuration:"
- log " Working directory: ${APP_DIR}"
- log " Config path: ${CONFIG_PATH}"
- log " Service user: ${RUN_USER}"
- log " Service group: ${RUN_GROUP}"
- log " Timer interval: ${TIMER_INTERVAL}"
- log " Peak hour: ${PEAK_START_HOUR} to ${PEAK_END_HOUR} (${PEAK_TZ})"
- log " Peak interval: ${PEAK_INTERVAL}"
- log " Off-peak interval: ${OFFPEAK_INTERVAL}"
- log " Push enabled: ${GIT_PUSH_ENABLED}"
- log " Push remote: ${GIT_PUSH_REMOTE}"
- log " Auth mode: ${AUTH_MODE}"
- log " Env file: ${ENV_FILE}"
- log ""
- log "Commands:"
- log " Check status: systemctl status ${SERVICE_NAME}.timer"
- log " View logs: journalctl -t ${SERVICE_NAME} -u ${SERVICE_NAME}.service -n 50 --no-pager"
- log " Manual run: sudo systemctl start ${SERVICE_NAME}.service"
- log " Force commit: sudo -u ${RUN_USER} /bin/bash ${APP_DIR}/scripts/run_update_and_commit.sh --force-commit ${CONFIG_PATH}"
- log ""
|