#!/bin/sh

echo_and_execute() {
    echo "executing: $@" && "$@"
}

copy_file() {
    from=$1
    to=$2
    filename=$(basename "$from")
    [ "$3" = "--sudo" ] &&
        echo_and_execute sudo cp -RPp "$from" "$to/$filename" ||
        {
            [ -e "$to/$filename" ] && rm "$to/$filename"
            echo_and_execute cp -RPp "$from" "$to/$filename"
        }
}

copy_dir() {
    from=$1
    to=$2
    prev_dir=$(pwd)
    cd "$from" || return 1
    find . -mindepth 1 -maxdepth 1 -type d | while read -r dir; do
        [ -d "$to/$dir" ] && rm -rf "$to/$dir"
        echo_and_execute cp -RPp "$dir" "$to/$dir"
    done
    find . -mindepth 1 -maxdepth 1 -type f | while read -r file; do
        copy_file "$file" "$to"
    done
    cd "$prev_dir" || return 1
}

sym_link() {
    ! [ -e "$1" ] && echo "skipping link, target does not exist: $1" && return
    [ -h "$2" ] && rm "$2"
    test -f "$2" -o -d "$2" && rm -rf "$2"
    echo_and_execute ln -s "$1" "$2"
}

echo "---- copying dotfiles ------------------"
. ./src_files/shell/profile

# copy over env/profile files used by shell(s)
copy_file src_files/shell/.profile $HOME
copy_file src_files/shell/profile $XDG_CONFIG_HOME
copy_file src_files/shell/rc $XDG_CONFIG_HOME
copy_file src_files/.config/zsh/.zshenv $HOME
# TODO: move this into xdg type dir if possible
copy_file src_files/.config/X11/xinit/.xinitrc $HOME

# copy over configs, executables, and scripts
copy_dir src_files/.config $XDG_CONFIG_HOME
copy_dir src_files/.local/bin $DIR_BIN
copy_dir src_files/.local/scripts $DIR_SCRIPTS

# macOS overrides as needed
case "$OSTYPE" in *darwin*) copy_dir src_files/bin_overrides_macos $DIR_BIN;; esac

# obsidian uses a per-vault config model, so copy to all target vaults/dirs
IFS=","; for obs_dir in $OBSIDIAN_WORKSPACES_TO_CONFIGURE; do
    ! [ -d "$obs_dir/.obsidian" ] && mkdir "$obs_dir/.obsidian"
    copy_dir "$XDG_CONFIG_HOME/obsidian" "$obs_dir/.obsidian"
done

# TODO: get reaper config set up
# case "$OSTYPE" in
#     (*darwin*)
#         sym_link "$XDG_CONFIG_HOME/REAPER" "$HOME/Library/Application Support/REAPER"
#         ;;
# esac

# copy settings/configs to /etc locations
case "$OSTYPE" in
    (*darwin*)
        ;;
    (*)
        copy_file src_files/etc/47-elogind.conf /etc/elogind/logind.conf.d --sudo
        ;;
esac

# set up themes and theme-switcher
! [ "$1" = "--skip-theme-config" ] && ./theme_config.sh

