#!/bin/bash

TSV="$1"

if [[ -n "$TSV" && "$TSV" == *.tsv ]]; then

    :

elif [[ -n "$TSV" ]]; then

    TSV="${TSV}.tsv"

else

    TSV="allfiles.tsv"

fi

TSV="$(realpath -m "$TSV")"


# -------------------- Проверка папок-исключений --------------------

EXCLUDES=()

for EXCLUDE in "${@:2}"; do

    if [[ ! -d "$EXCLUDE" ]]; then
        echo "ERROR: Exclusion directory does not exist:"
        echo "    $EXCLUDE"
        exit 1
    fi

    EXCLUDE="$(realpath "$EXCLUDE")"
    EXCLUDES+=("$EXCLUDE")

done


# -------------------- Формирование find --------------------

FIND_ARGS=(
    find /
    '('
    -path /proc
    -o -path /sys
    -o -path /dev
    -o -path /run
)

for EXCLUDE in "${EXCLUDES[@]}"; do
    FIND_ARGS+=(
        -o
        -path "$EXCLUDE"
    )
done

FIND_ARGS+=(
    \)
    -prune
    -o
    -type f
    -printf '%p\t%s\n'
)

# -------------------- Информация пользователю --------------------

echo
echo "A list of all files in the system will be created in:"
echo
echo "    $TSV"
echo

if [[ -e "$TSV" ]]; then
    echo "WARNING: The file already exists and will be overwritten."
else
    echo "The file does not exist and will be created."
fi

if [[ ${#EXCLUDES[@]} -gt 0 ]]; then
    echo
    echo "The following directories will be excluded:"
    echo

    for EXCLUDE in "${EXCLUDES[@]}"; do
        echo "    $EXCLUDE"
    done
fi

echo
read -n 1 -r -s -p "Press any key to continue, or Ctrl+C to stop..."
echo
echo


# -------------------- Дамп --------------------

echo "Dump all files list to $TSV ..."

sudo "${FIND_ARGS[@]}" \
    2>/dev/null > "$TSV"


# -------------------- SQLite --------------------

echo
echo "File list successfully created:"
echo
echo "    $TSV"
echo

read -n 1 -r -s -p "Press any key to convert to SQLite3, or Ctrl+C to stop..."
echo
echo

echo "Converting $TSV to SQLite3 ..."

tsv2sqlite3 "$TSV"

echo
echo "Conversion completed."