#!/usr/bin/env bash

# absolute path to your git folder
dotDir="${HOME}/.dotfiles"

display_help(){
    echo "Usage: ${0##*/} [flag]"
    echo "Check if '${dotDir}' is yours dotfiles directory path"
    echo "No flags == DRY RUN"
    echo "-d, --dry-run == link files"
    echo "-l, --link == link files"
    echo "-F, --force == link files with overwrite"
    exit 2
}

create_dirs(){
    file="$1"
    new="${file//${dotDir}/${HOME}}"
    newDir="${new%/*}"
    mkdir -p "$newDir"
}

dry_run(){
    file="$1"
    symlink="${file//${dotDir}/${HOME}}"
    [[ ! -f $symlink ]] && echo "DRY RUN: Linking ${file} --> ${symlink}"
}

link_file(){
    file="$1"
    create_dirs "$file"
    ln -sv "$file" "$new" 2>/dev/null
}

link_force(){
    file="$1"
    create_dirs "$file"
    ln -sfv "$file" "$new"
}

[[ ! -d $dotDir || $# -gt 1 ]] && display_help

for file in $(find "$dotDir" -type f -not -path "*\.git*"); do
    case "$1" in
        -d|--dry-run) dry_run "$file";;
        -l|--link) link_file "$file";;
        -f|--force) link_force "$file";;
        -h|--help) display_help;;
        *) display_help;;
    esac
done
