#!/bin/bash

SCRIPT_DIR="$(
    cd -- "$(dirname "$0")" >/dev/null 2>&1 || exit 1
    pwd -P
)"
IGNORED_FILES="$(cat "$SCRIPT_DIR/.installer/ignored")"
EXECUTABLE_FILES="$(cat "$SCRIPT_DIR/.installer/executables")"

function is_ignored() {
    while IFS= read -r line; do
        grep -Eq "$line" <<<"${1:?}" && return 0
    done <<<"$IGNORED_FILES"
    return 1
}

function is_executable() {
    while IFS= read -r line; do
        grep -Eq "$line" <<<"${1:?}" && return 0
    done <<<"$EXECUTABLE_FILES"
    return 1
}

function is_identical() {
    local src dst src_sum dst_sum
    src="$SCRIPT_DIR/$1"
    dst="$HOME/$1"

    ! [ -e "$dst" ] && return 1

    src_sum="$(sha256sum "$src" | cut -d' ' -f1)"
    dst_sum="$(sha256sum "$dst" | cut -d' ' -f1)"

    [[ "$src_sum" == "$dst_sum" ]] && return 0
    return 1
}

function install() {
    local file dir src dst perform_copy

    echo "Copying files... 💾"

    while IFS= read -r file; do
        [[ "$file" == *".git/"* ]] && continue

        perform_copy=true
        file="${file#"$SCRIPT_DIR/"}"
        dir="$(dirname "$HOME/$file")"
        src="$SCRIPT_DIR/$file"
        dst="$HOME/$file"

        if is_ignored "$file"; then
            echo "IGNORE: '$file'"
            continue
        elif ! [ -d "$dir" ]; then
            echo "MKDIR : '$dir'"
            mkdir -p "$dir" || exit 10
        elif is_identical "$file"; then
            echo "NODIFF: '$file'"
            perform_copy=false
        fi

        if $perform_copy; then
            if [ -e "$dst" ]; then
                echo "DIFF  : '$file'"
            else
                echo "NEW   : '$file'"
            fi
            cp --no-dereference "$src" "$dst" || exit 20
        fi

        if is_executable "$file" && ! [ -x "$dst" ]; then
            echo "+EXEC : '$file'"
            chmod +x "$dst"
        fi
    done <<<"$(find "$SCRIPT_DIR" -type f && find "$SCRIPT_DIR" -type l)"
    echo
}

function override_bg() {
    local default=~/.local/share/bg override=~/Pictures/bg

    ! [ -e "$override" ] && return

    echo "Overriding default background with '$override'."
    ln -sfn "$override" "$default"
    echo
}

install
override_bg
"$SCRIPT_DIR/.local/bin/i3-config-builder"
echo "Done! 👌"
