start 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. #!/bin/bash
  2. # Dotfiles sync script
  3. set -euo pipefail
  4. # Configuration
  5. hostname_id=$(uname -n)
  6. checkout_dir=$HOME/.dofiles
  7. script_dir=$checkout_dir/dotfiles
  8. dots_dir=$checkout_dir/dotfiles/dots
  9. dots_host_dir=$checkout_dir/dotfiles/dots.$hostname_id
  10. repo="https://git.capella.pro/capella/dotfiles.git"
  11. ProgName=$(basename "$0")
  12. # Colors for output
  13. RED='\033[0;31m'
  14. GREEN='\033[0;32m'
  15. YELLOW='\033[1;33m'
  16. NC='\033[0m' # No Color
  17. # Logging functions
  18. log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
  19. log_warn() { echo -e "${YELLOW}[WARN]${NC} $*" >&2; }
  20. log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
  21. # Get group names for the current host (sorted, one per line)
  22. get_groups() {
  23. local groups_file="$script_dir/groups.$hostname_id"
  24. if [[ -f "$groups_file" ]]; then
  25. grep -v '^\s*#' "$groups_file" | grep -v '^\s*$' | sort
  26. fi
  27. }
  28. # Get combined sync list (common + groups + host-specific, deduplicated)
  29. get_sync_list() {
  30. {
  31. cat "$script_dir/to_sync" 2>/dev/null || true
  32. while IFS= read -r group; do
  33. cat "$script_dir/to_sync.@$group" 2>/dev/null || true
  34. done < <(get_groups)
  35. cat "$script_dir/to_sync.$hostname_id" 2>/dev/null || true
  36. } | grep -v '^\s*$' | sort -u || true
  37. }
  38. # Resolve source path: common -> groups (alpha) -> host-specific (last wins)
  39. resolve_source() {
  40. local p="$1"
  41. local result="$dots_dir/$p"
  42. while IFS= read -r group; do
  43. if [[ -e "$script_dir/dots.@$group/$p" ]]; then
  44. result="$script_dir/dots.@$group/$p"
  45. fi
  46. done < <(get_groups)
  47. if [[ -e "$dots_host_dir/$p" ]]; then
  48. result="$dots_host_dir/$p"
  49. fi
  50. echo "$result"
  51. }
  52. # Check if a file contains @host or @group markers
  53. file_has_markers() {
  54. grep -qE '@(host|group) ' "$1" 2>/dev/null
  55. }
  56. # Check if any file in a directory tree contains markers
  57. dir_has_markers() {
  58. grep -rqlE '@(host|group) ' "$1" 2>/dev/null
  59. }
  60. # Detect the comment style from the first marker line in a file
  61. # Returns "block" for /* */ style, or the line-comment prefix (# // ; --)
  62. detect_comment_style() {
  63. local src="$1"
  64. local marker_line
  65. marker_line=$(grep -m1 -E '@(host|group) ' "$src")
  66. # Extract everything before @host or @group
  67. local prefix="${marker_line%%@*}"
  68. # Trim trailing whitespace
  69. prefix="${prefix%"${prefix##*[![:space:]]}"}"
  70. # Check if it's a block comment opener
  71. if [[ "$prefix" == "/*" ]]; then
  72. echo "block"
  73. else
  74. echo "$prefix"
  75. fi
  76. }
  77. # Process a file with @host/@group markers, outputting only matching sections
  78. process_markers() {
  79. local src="$1"
  80. local in_block=0
  81. local include_block=0
  82. # Pre-load groups into an associative array for fast lookup
  83. declare -A host_groups
  84. while IFS= read -r g; do
  85. host_groups["$g"]=1
  86. done < <(get_groups)
  87. while IFS= read -r line || [[ -n "$line" ]]; do
  88. if [[ $in_block -eq 0 ]]; then
  89. if [[ "$line" =~ @host[[:space:]]+([^[:space:]]+) ]]; then
  90. in_block=1
  91. if [[ "${BASH_REMATCH[1]}" == "$hostname_id" ]]; then
  92. include_block=1
  93. else
  94. include_block=0
  95. fi
  96. elif [[ "$line" =~ @group[[:space:]]+([^[:space:]]+) ]]; then
  97. in_block=1
  98. if [[ -v "host_groups[${BASH_REMATCH[1]}]" ]]; then
  99. include_block=1
  100. else
  101. include_block=0
  102. fi
  103. elif [[ "$line" =~ @end ]]; then
  104. # Stray @end outside a block, skip it
  105. continue
  106. else
  107. printf '%s\n' "$line"
  108. fi
  109. else
  110. if [[ "$line" =~ @end ]]; then
  111. in_block=0
  112. include_block=0
  113. elif [[ $include_block -eq 1 ]]; then
  114. printf '%s\n' "$line"
  115. fi
  116. fi
  117. done < "$src"
  118. if [[ $in_block -eq 1 ]]; then
  119. log_warn "Unclosed @host/@group block in $src"
  120. fi
  121. }
  122. # Ensure we cleanup on exit
  123. trap 'cd "$HOME"' EXIT
  124. # Create checkout directory if needed
  125. mkdir -p "$checkout_dir"
  126. sub_help(){
  127. local groups
  128. groups=$(get_groups | tr '\n' ', ' | sed 's/,$//')
  129. cat << EOF
  130. Usage: $ProgName <subcommand> [options]
  131. Subcommands:
  132. sync [--machine|--group <name>] [dot_file]
  133. Sync dotfiles (optionally add a new dotfile)
  134. --machine: add to host-specific config ($hostname_id)
  135. --group <name>: add to group-specific config
  136. list List currently synced dotfiles
  137. status Show git status of dotfiles repo
  138. Host: $hostname_id
  139. Groups: ${groups:-none}
  140. Resolution order: common -> groups (alpha) -> host-specific
  141. Common dotfiles: dots/ + to_sync
  142. Group dotfiles: dots.@<group>/ + to_sync.@<group>
  143. Host overrides: dots.$hostname_id/ + to_sync.$hostname_id
  144. In-file markers:
  145. # @host <name> ... # @end (host-specific block)
  146. # @group <name> ... # @end (group-specific block)
  147. Files with markers are processed and written (not symlinked).
  148. For help with each subcommand run:
  149. $ProgName <subcommand> -h|--help
  150. EOF
  151. }
  152. sub_sync(){
  153. # Clone repo if it doesn't exist
  154. if [[ ! -d "$checkout_dir/dotfiles/.git" ]]; then
  155. log_info "Cloning dotfiles repository..."
  156. cd "$checkout_dir"
  157. if ! git clone "$repo"; then
  158. log_error "Failed to clone repository"
  159. exit 1
  160. fi
  161. cd "$script_dir"
  162. git submodule init
  163. git submodule update
  164. fi
  165. # Navigate to script directory
  166. cd "$script_dir"
  167. # Get current branch
  168. current_branch=$(git branch --show-current)
  169. log_info "Pulling latest changes from $current_branch..."
  170. git pull origin "$current_branch" || log_warn "Git pull failed, continuing anyway"
  171. git submodule update --init --recursive
  172. # Parse flags for adding new dotfiles
  173. local machine_specific=0
  174. local group_target=""
  175. if [[ "${1:-}" == "--machine" ]]; then
  176. machine_specific=1
  177. shift
  178. elif [[ "${1:-}" == "--group" ]]; then
  179. group_target="${2:-}"
  180. if [[ -z "$group_target" ]]; then
  181. log_error "--group requires a group name"
  182. exit 1
  183. fi
  184. shift 2
  185. fi
  186. # Add new dotfile if provided
  187. if [ -n "${1:-}" ]; then
  188. local file_to_add="$1"
  189. # Validate that file exists
  190. if [[ ! -e "$HOME/$file_to_add" ]]; then
  191. log_error "File $HOME/$file_to_add does not exist"
  192. exit 1
  193. fi
  194. log_info "Adding new dotfile: $file_to_add"
  195. real_path=$(realpath "$HOME/$file_to_add")
  196. to_copy=${real_path#"$HOME/"}
  197. if [[ $machine_specific -eq 1 ]]; then
  198. target_dots_dir="$dots_host_dir"
  199. sync_file="$script_dir/to_sync.$hostname_id"
  200. log_info "Adding as host-specific ($hostname_id)"
  201. elif [[ -n "$group_target" ]]; then
  202. target_dots_dir="$script_dir/dots.@$group_target"
  203. sync_file="$script_dir/to_sync.@$group_target"
  204. log_info "Adding as group-specific (@$group_target)"
  205. else
  206. target_dots_dir="$dots_dir"
  207. sync_file="$script_dir/to_sync"
  208. fi
  209. # Create parent directory structure
  210. mkdir -p "$(dirname "$target_dots_dir/$to_copy")"
  211. # Copy to dots directory
  212. if cp -R "$real_path" "$target_dots_dir/$to_copy"; then
  213. log_info "Copied $file_to_add to $target_dots_dir/$to_copy"
  214. else
  215. log_error "Failed to copy $file_to_add"
  216. exit 1
  217. fi
  218. # Add to sync file if not already there
  219. if ! grep -qxF "$to_copy" "$sync_file" 2>/dev/null; then
  220. echo "$to_copy" >> "$sync_file"
  221. log_info "Added $to_copy to $(basename "$sync_file")"
  222. else
  223. log_info "$to_copy already in $(basename "$sync_file")"
  224. fi
  225. # Remove original and create symlink
  226. rm -rf "$real_path"
  227. ln -s "$target_dots_dir/$to_copy" "$real_path"
  228. log_info "Created symlink: $real_path -> $target_dots_dir/$to_copy"
  229. fi
  230. # Stage tracked files from all source directories
  231. log_info "Staging changes..."
  232. get_sync_list | while IFS= read -r p; do
  233. if [[ -e "$dots_dir/$p" ]]; then
  234. git add "$dots_dir/$p"
  235. fi
  236. while IFS= read -r group; do
  237. if [[ -e "$script_dir/dots.@$group/$p" ]]; then
  238. git add "$script_dir/dots.@$group/$p"
  239. fi
  240. done < <(get_groups)
  241. if [[ -e "$dots_host_dir/$p" ]]; then
  242. git add "$dots_host_dir/$p"
  243. fi
  244. done
  245. git add start to_sync
  246. # Stage host-specific, group-specific, and groups files
  247. for f in to_sync.* groups.*; do
  248. [[ -f "$f" ]] && git add "$f"
  249. done
  250. for d in dots.*/; do
  251. [[ -d "$d" ]] && git add "$d"
  252. done
  253. # Commit and push if there are changes
  254. if git diff --cached --quiet; then
  255. log_info "No changes to commit"
  256. else
  257. log_info "Committing changes..."
  258. if git commit -m "Sync: $(date '+%Y-%m-%d %H:%M:%S')"; then
  259. log_info "Pushing to remote..."
  260. git remote add origin "$repo" 2>/dev/null || true
  261. if git push -u origin "$current_branch"; then
  262. log_info "Successfully pushed changes"
  263. else
  264. log_error "Failed to push changes"
  265. exit 1
  266. fi
  267. else
  268. log_error "Failed to commit changes"
  269. exit 1
  270. fi
  271. fi
  272. # Deploy a single file: process markers or symlink
  273. deploy_file() {
  274. local src="$1"
  275. local dest="$2"
  276. mkdir -p "$(dirname "$dest")"
  277. if file_has_markers "$src"; then
  278. # File has markers — process and write (not symlink)
  279. if [[ -L "$dest" ]]; then
  280. rm "$dest"
  281. fi
  282. local comment_style
  283. comment_style=$(detect_comment_style "$src")
  284. {
  285. if [[ "$comment_style" == "block" ]]; then
  286. echo "/* DO NOT EDIT - Generated by dotsync from: $src */"
  287. else
  288. echo "$comment_style DO NOT EDIT - Generated by dotsync from:"
  289. echo "$comment_style $src"
  290. fi
  291. echo ""
  292. process_markers "$src"
  293. } > "$dest.dotsync_tmp"
  294. # Only update if content changed
  295. if [[ -f "$dest" ]] && cmp -s "$dest" "$dest.dotsync_tmp"; then
  296. rm "$dest.dotsync_tmp"
  297. else
  298. [[ -e "$dest" ]] && rm "$dest"
  299. mv "$dest.dotsync_tmp" "$dest"
  300. chmod --reference="$src" "$dest"
  301. log_info "Processed: $dest (from $src)"
  302. fi
  303. else
  304. # No markers — symlink
  305. if [[ -L "$dest" ]] && [[ "$(readlink "$dest")" == "$src" ]]; then
  306. return # Already correctly linked
  307. fi
  308. if [[ -e "$dest" ]] || [[ -L "$dest" ]]; then
  309. log_warn "Removing existing $dest"
  310. rm -rf "$dest"
  311. fi
  312. if ln -s "$src" "$dest"; then
  313. log_info "Linked: $dest -> $src"
  314. else
  315. log_error "Failed to create symlink for $(basename "$dest")"
  316. fi
  317. fi
  318. }
  319. # Deploy dotfiles (symlink or process markers)
  320. log_info "Deploying dotfiles for $hostname_id..."
  321. get_sync_list | while IFS= read -r p; do
  322. local source
  323. source=$(resolve_source "$p")
  324. local destination="$HOME/$p"
  325. if [[ ! -e "$source" ]]; then
  326. log_warn "Source $source does not exist, skipping"
  327. continue
  328. fi
  329. if [[ -d "$source" ]]; then
  330. if dir_has_markers "$source"; then
  331. # Directory contains markers — expand into per-file operations
  332. # Remove directory-level symlink if present
  333. if [[ -L "$destination" ]]; then
  334. log_warn "Replacing directory symlink $destination with expanded files"
  335. rm "$destination"
  336. fi
  337. mkdir -p "$destination"
  338. # Walk all files in the source directory
  339. while IFS= read -r src_file; do
  340. local rel="${src_file#"$source/"}"
  341. deploy_file "$src_file" "$destination/$rel"
  342. done < <(find "$source" -type f | sort)
  343. else
  344. # No markers in directory — symlink the whole directory
  345. if [[ -L "$destination" ]] && [[ "$(readlink "$destination")" == "$source" ]]; then
  346. continue # Already correctly linked
  347. fi
  348. if [[ -e "$destination" ]] || [[ -L "$destination" ]]; then
  349. log_warn "Removing existing $destination"
  350. rm -rf "$destination"
  351. fi
  352. if ln -s "$source" "$destination"; then
  353. log_info "Linked: $destination -> $source"
  354. else
  355. log_error "Failed to create symlink for $p"
  356. fi
  357. fi
  358. else
  359. # Single file entry
  360. deploy_file "$source" "$destination"
  361. fi
  362. done
  363. log_info "Sync complete!"
  364. }
  365. sub_list(){
  366. echo "Host: $hostname_id"
  367. local groups
  368. groups=$(get_groups | tr '\n' ', ' | sed 's/,$//')
  369. if [[ -n "$groups" ]]; then
  370. echo "Groups: $groups"
  371. fi
  372. echo ""
  373. if [[ -f "$script_dir/to_sync" ]]; then
  374. echo "Common dotfiles (to_sync):"
  375. while IFS= read -r p; do
  376. [[ -z "$p" ]] && continue
  377. local source
  378. source=$(resolve_source "$p")
  379. local tag=""
  380. if [[ "$source" == "$dots_host_dir/"* ]]; then
  381. tag=" [override: $hostname_id]"
  382. elif [[ "$source" == *"/dots.@"* ]]; then
  383. local gname
  384. gname=$(echo "$source" | sed 's|.*dots\.@\([^/]*\)/.*|\1|')
  385. tag=" [override: @$gname]"
  386. fi
  387. local marker_tag=""
  388. if [[ -f "$source" ]] && file_has_markers "$source"; then
  389. marker_tag=" [processed]"
  390. fi
  391. if [[ -L "$HOME/$p" ]] || [[ -f "$HOME/$p" ]] || [[ -d "$HOME/$p" ]]; then
  392. echo " + $p$tag$marker_tag"
  393. else
  394. echo " - $p (not deployed)$tag$marker_tag"
  395. fi
  396. done < "$script_dir/to_sync"
  397. fi
  398. # Group-specific dotfiles
  399. while IFS= read -r group; do
  400. local gsync="$script_dir/to_sync.@$group"
  401. if [[ -f "$gsync" ]] && [[ -s "$gsync" ]]; then
  402. echo ""
  403. echo "Group dotfiles (to_sync.@$group):"
  404. while IFS= read -r p; do
  405. [[ -z "$p" ]] && continue
  406. if [[ -L "$HOME/$p" ]] || [[ -f "$HOME/$p" ]] || [[ -d "$HOME/$p" ]]; then
  407. echo " + $p"
  408. else
  409. echo " - $p (not deployed)"
  410. fi
  411. done < "$gsync"
  412. fi
  413. done < <(get_groups)
  414. # Host-specific dotfiles
  415. if [[ -f "$script_dir/to_sync.$hostname_id" ]] && [[ -s "$script_dir/to_sync.$hostname_id" ]]; then
  416. echo ""
  417. echo "Host-specific dotfiles (to_sync.$hostname_id):"
  418. while IFS= read -r p; do
  419. [[ -z "$p" ]] && continue
  420. if [[ -L "$HOME/$p" ]] || [[ -f "$HOME/$p" ]] || [[ -d "$HOME/$p" ]]; then
  421. echo " + $p"
  422. else
  423. echo " - $p (not deployed)"
  424. fi
  425. done < "$script_dir/to_sync.$hostname_id"
  426. fi
  427. }
  428. sub_status(){
  429. if [[ ! -d "$script_dir/.git" ]]; then
  430. log_error "Dotfiles repository not found"
  431. exit 1
  432. fi
  433. cd "$script_dir"
  434. log_info "Host: $hostname_id"
  435. log_info "Git status:"
  436. git status
  437. }
  438. subcommand=${1:-}
  439. case $subcommand in
  440. "" | "-h" | "--help")
  441. sub_help
  442. ;;
  443. sync|list|status)
  444. shift
  445. "sub_${subcommand}" "$@"
  446. ;;
  447. *)
  448. log_error "'$subcommand' is not a known subcommand."
  449. echo " Run '$ProgName --help' for a list of known subcommands." >&2
  450. exit 1
  451. ;;
  452. esac