#!/bin/sh

set -e

SCRIPT_DIR=$(cd -P -- "$(dirname -- "$0")" && pwd -P)

CONFIG="${XDG_CONFIG_HOME:-$HOME/.config}"
mkdir -p "$CONFIG"

link() {
  src="$1"
  dst="$2"

  if [ -e "$dst" ] || [ -L "$dst" ]; then
    rm -rf -- "$dst"
  fi

  ln -sf -- "$src" "$dst"
}

copy_if_missing() {
  src="$1"
  dst="$2"

  if [ ! -e "$dst" ] && [ ! -L "$dst" ]; then
    cp -a -- "$src" "$dst"
  fi
}

link_abook() {
  mkdir -p "$HOME/.abook"
  link "$SCRIPT_DIR/abook/abookrc" "$HOME/.abook/abookrc"
}

link_gdb() {
  link "$SCRIPT_DIR/gdb" "$CONFIG/gdb"
}

link_gitconfig() {
  link "$SCRIPT_DIR/git" "$CONFIG/git"
}

link_mpd() {
  link "$SCRIPT_DIR/mpd" "$CONFIG/mpd"
}

link_ncmpcpp() {
  link "$SCRIPT_DIR/ncmpcpp" "$CONFIG/ncmpcpp"
}

link_neovim() {
  link "$SCRIPT_DIR/nvim" "$CONFIG/nvim"
}

link_newsboat() {
  mkdir -p "$CONFIG/newsboat"
  link "$SCRIPT_DIR/newsboat/config" "$CONFIG/newsboat/config"
}

copy_npmrc() {
  copy_if_missing "$SCRIPT_DIR/npm/npmrc" "$HOME/.npmrc"
}

link_nexrc() {
  link "$SCRIPT_DIR/nexrc/nexrc" "$HOME/.nexrc"
}

link_taskwarrior() {
  link "$SCRIPT_DIR/taskwarrior" "$CONFIG/task"
}

link_tmux() {
  link "$SCRIPT_DIR/tmux" "$CONFIG/tmux"
}

link_vit() {
  link "$SCRIPT_DIR/vit" "$CONFIG/vit"
}

link_wyrdrc() {
  link "$SCRIPT_DIR/wyrd/wyrdrc" "$HOME/.wyrdrc"
}

link_xinitrc() {
  link "$SCRIPT_DIR/X11/xinitrc" "$HOME/.xinitrc"
}

link_zsh() {
  link "$SCRIPT_DIR/zsh/zshrc" "$HOME/.zshrc"
  link "$SCRIPT_DIR/zsh/zshenv" "$HOME/.zshenv"
  link "$SCRIPT_DIR/zsh/zprofile" "$HOME/.zprofile"
}

link_abook
link_gdb
link_gitconfig
link_mpd
link_ncmpcpp
link_neovim
link_newsboat
copy_npmrc
link_nexrc
link_taskwarrior
link_tmux
link_vit
link_wyrdrc
link_xinitrc
link_zsh
