dotfiles.sh

· erock's pastes · raw

expires: 2025-03-18

 1#!/usr/bin/env bash
 2
 3TRACKED_FILES=(
 4    bin/
 5    dot_config/
 6    dot/gitconfig
 7    dot/tmux.conf
 8    dot/mbsyncrc
 9    dot_gnupg/gpg-agent.conf
10    dot_ssh/config
11    dot_mblaze/mblaze
12    dot/msmtprc
13    dot/npmrc
14)
15
16TRACKED_LOCATIONS=(
17    ~/bin/
18    ~/.config/
19    ~/.gitconfig
20    ~/.tmux.conf
21    ~/.mbsyncrc
22    ~/.gnupg/gpg-agent.conf
23    ~/.ssh/config
24    ~/.mblaze/profile
25    ~/.msmtprc
26    ~/.npmrc
27)
28
29find_files() {
30    if [[ ${TRACKED_FILES[$1]} == */ ]]; then
31        find "$PWD/${TRACKED_FILES[$1]}" -type d -exec find {} -maxdepth 1 -type f \; | sed "s|$PWD/${TRACKED_FILES[$1]}||" | sed "s|^/||"
32    fi
33}
34
35link_file() {
36    if [[ ! -L $2 && ! -f $2 && ! -d $2 ]]; then
37        echo "Creating a link from $1 to $2"
38        mkdir -p $2
39        rmdir $2
40        ln -s $1 $2
41    fi
42}
43export -f link_file
44
45unlink_file() {
46    if [[ -L $1 ]]; then
47        echo "Unlinking $1"
48        unlink "$1"
49    fi
50}
51export -f unlink_file
52
53move_file() {
54    if [[ ! -L $1 ]] && [[ -f $1 || -d $1 ]]; then
55        echo "Moving $1 to backup/$1"
56        mkdir -p "backup/$1"
57        rmdir "backup/$1"
58        mv $1 "backup/$1"
59    fi
60}
61export -f move_file
62
63for ((i = 0; i < ${#TRACKED_FILES[@]}; ++i)); do
64    if [ "$1" == "cleanup" ]; then
65        unlink_file "${TRACKED_LOCATIONS[$i]}"
66        find_files "$i" | xargs -I {} bash -c "unlink_file ${TRACKED_LOCATIONS[$i]}{}"
67        continue
68    fi
69
70    if [ "$1" == "override" ]; then
71        move_file ${TRACKED_LOCATIONS[$i]}
72        find_files "$i" | xargs -I {} bash -c "move_file ${TRACKED_LOCATIONS[$i]}{}"
73    fi
74
75    if [ "$1" != "cleanup" ]; then
76        link_file "$PWD/${TRACKED_FILES[$i]}" "${TRACKED_LOCATIONS[$i]}"
77        find_files "$i" | xargs -I {} bash -c "link_file $PWD/${TRACKED_FILES[$i]}{} ${TRACKED_LOCATIONS[$i]}{}"
78    fi
79done