start 16 KB

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