#!/usr/bin/env bash # install-ccusage-sync.sh - Install multi-device AI coding usage synchronization. set -euo pipefail IFS=$'\n\t' readonly SCRIPT_NAME="${0##*/}" readonly INSTALLER_URL_DEFAULT='https://opengist.resetrix.work/weehong/ai-coding-agent/raw/HEAD/sync-ccusage.sh' readonly CRON_ENTRY='*/5 * * * * /bin/bash $HOME/sync-ccusage.sh >/dev/null 2>&1' INSTALLER_URL="${CCUSAGE_INSTALLER_URL:-$INSTALLER_URL_DEFAULT}" DRY_RUN=0 usage() { cat <&2; exit 1; } trap 'rc=$?; (( rc )) && printf "\033[1;31m[%s] failed at line %s (exit %d)\033[0m\n" "${SCRIPT_NAME%.sh}" "$LINENO" "$rc" >&2' ERR while (( $# )); do case "$1" in --dry-run) DRY_RUN=1 ;; -h|--help) usage; exit 0 ;; *) die "Unknown argument: $1 (try --help)" ;; esac shift done (( EUID != 0 )) || die "Do not run as root. Run as your normal user." for tool in bash curl grep head mktemp; do command -v "$tool" >/dev/null 2>&1 || die "Missing required tool: $tool" done if [[ -r /etc/os-release ]]; then # shellcheck disable=SC1091 . /etc/os-release case "${ID:-}:${ID_LIKE:-}" in *ubuntu*|*debian*) : ;; *) die "Unsupported distro: ${PRETTY_NAME:-unknown}." ;; esac else die "/etc/os-release not found." fi STAGE="$(mktemp -d -t ccusage-sync.XXXXXX)" trap 'rm -rf "$STAGE"' EXIT DOWNLOADED_INSTALLER="$STAGE/sync-ccusage.sh" log "Downloading canonical installer..." curl --proto '=https' --tlsv1.2 -fsSL --max-time 60 --retry 2 \ "$INSTALLER_URL" -o "$DOWNLOADED_INSTALLER" [[ -s "$DOWNLOADED_INSTALLER" ]] || die "Downloaded installer is empty." head -n1 "$DOWNLOADED_INSTALLER" | grep -qE '^#!/usr/bin/env bash$' \ || die "Downloaded installer has an unexpected shebang." bash -n "$DOWNLOADED_INSTALLER" \ || die "Downloaded installer failed Bash syntax validation." grep -qF 'hetzner-ccusage-storage-box' "$DOWNLOADED_INSTALLER" \ || die "Downloaded installer does not contain the expected SSH target." if (( DRY_RUN )); then log "Validated installer: $INSTALLER_URL" log "Would run the installer as the current user." log "Would install: $HOME/sync-ccusage.sh" log "Would install cron: $CRON_ENTRY" exit 0 fi log "Running the CCUsage installer..." bash "$DOWNLOADED_INSTALLER" install [[ -x "$HOME/sync-ccusage.sh" ]] \ || die "Installed script is missing or not executable: $HOME/sync-ccusage.sh" bash -n "$HOME/sync-ccusage.sh" \ || die "Installed script failed Bash syntax validation." crontab -l 2>/dev/null | grep -Fqx "$CRON_ENTRY" \ || die "The five-minute CCUsage cron entry was not installed." log "CCUsage sync installation verified." log "Synced logs are available under: $HOME/.ccusage-synced-logs" log "Cron schedule: $CRON_ENTRY"