#! /usr/bin/env nix-shell
#! nix-shell -i bash -p bash gum fd ripgrep eza trash-cli zip unzip

root_directories=(
    /srv/pool/multimedia/media/Library/comics
    /srv/pool/multimedia/media/Library/manga/manga
    /srv/pool/multimedia/media/Library/manga/webtoons
    /srv/pool/multimedia/media/Library/manga/español
    /srv/pool/multimedia/media/Library/webtoons
)

newname() {
    echo "$1" | sed -E "s/$2/$3/g"
}

separator() {
    gum style --foreground 7 _________________________
}
announce_changes() {
    echo "Renaming:"
    gum style --foreground 1 "$1"
    echo "Into:"
    gum style --foreground 2 "$2"
    separator
}

rename_file() {
    while IFS= read -r file; do
        local original_name
        original_name=$(basename "$file")
        local new_name
        new_name=$(newname "$(basename "$file")" "$2" "$3")

        announce_changes "$original_name" "$new_name"
        command mv -n "$(dirname "$file")"/{"$original_name","$new_name"}
    done < <(fd "$1" --absolute-path -tf -s "${root_directories[@]}")
}

rename_directory() {
    while IFS= read -r dir; do
        local new_name
        new_name=$(newname "$(basename "$dir")" "$2" "$3")
        local new_dir
        new_dir=$(dirname "$dir")/$new_name

        announce_changes "$dir" "$new_dir"
        echo "Processing..."
        if [ ! -d "$new_dir" ]; then
            echo "$(basename "$new_dir") doesn't exist. Creating it."
            command mkdir -p "$new_dir"
        fi
        if [ -d "$new_dir" ]; then
            echo "$(basename "$new_dir") has been created!, moving the following files:"
            eza "$dir"
            fd . "$dir" -x mv -n {} "$(realpath "$new_dir")"
        fi
        separator
    done < <(fd "$1" --absolute-path -td -s "${root_directories[@]}")
}

rename_numbered_files() {
    while IFS= read -r file; do
        local original_name
        original_name=$(basename "$file")
        local new_name

        new_name=$(echo "$original_name" | sed -E 's/(.*) - 0*([[:digit:]]+)(\.cbz)/\1 #\2\3/')

        if [[ "$new_name" != "$original_name" ]]; then
            announce_changes "$original_name" "$new_name"
            command mv -n "$(dirname "$file")"/{"$original_name","$new_name"}
        fi
    done < <(fd --absolute-path -tf -e cbz '\-[[:space:]]0*[[:digit:]]+' "${root_directories[@]}")
}

# Check directory existence
for dir in "${root_directories[@]}"; do
    if [ -d "$dir" ]; then
        continue
    fi
    echo "directory doesn't exist... creating $dir"
    mkdir -vp "$dir"
done

# Fix numbered issues (For migrating from old directory)
rename_numbered_files

# Capitalize Special words
words=(special tpb full annual)
Words=(Special TPB Full Annual)
counter=0
for word in "${words[@]}"; do
    while IFS= read -r file; do
        new_name=$(newname "$(basename "$file")" "$word" "${Words[$counter]}")
        echo "Inproper capitalization of the word"
        gum style --foreground 1 "$word"
        echo "adjusting it into"
        gum style --foreground 2 "${Words[$counter]}"
        announce_changes "$(basename "$file")" "$new_name"
        command mv -n "$(dirname "$file")"/{"$(basename "$file")","$new_name"}
    done < <(fd "$word" --absolute-path -tf -s "${root_directories[@]}")
    counter=$((counter + 1))
done

# Rename Year files
# set regex_year_grep "\([[:digit:]]{4}\)"
# set regex_year_string "(\()(\d{4})(\))"
# rename_directory $regex_year_grep $regex_year_string \$2
# rename_file $regex_year_grep $regex_year_string \$2

# Rename #_ downloads
regex_hashtag="#_"
rename_directory $regex_hashtag $regex_hashtag "#"
rename_file $regex_hashtag $regex_hashtag "#"

# Rename ~ to :
# rename_directory " ~ " " ~ " ": "
# rename_file " ~ " " ~ " ": "

rename_keywords() {
    # Followed by digit
    local regex_digit_fd="$1 \d+"
    local regex_digit="($1 )([[:digit:]]+)"
    rename_directory "$regex_digit_fd" "$regex_digit" "\1#\2"
    rename_file "$regex_digit_fd" "$regex_digit" "\1#\2"
    # Without digit
    regex="#$1"
    rename_directory "$regex" "$regex" "$1"
    rename_file "$regex" "$regex" "$1"
}

rename_keywords TPB
rename_keywords Special
rename_keywords Annual

# Rename #Full
rename_directory " #Full" " #Full" ""
rename_file " #Full" " #Full" ""

# Rename double space
rename_directory "  " "  " " "
rename_file "  " "  " " "

# Fix names
wrongnames=(
    "Transformers: Spotlight"
    "Dr. Stone"
    i-dont-want-this-kind-of-hero
    pure-of-heart
    scoob-and-shag
    stick-n-poke
    "Houseki no Kuni"
    "Gantz E"
    "Gantz G"
)
rightname=(
    "Transformers Spotlight:"
    "Dr. STONE"
    "I DON'T WANT THIS KIND OF HERO"
    "Pure of Heart"
    "Scoob and Shag"
    "Stick n' Poke"
    "Land of the Lustrous"
    "Gatz:E"
    "Gantz:G"
)
counter=0
for wrongname in "${wrongnames[@]}"; do
    rename_directory "$wrongname" "$wrongname" "${rightname[$counter]}"
    rename_file "$wrongname" "$wrongname" "${rightname[$counter]}"
    counter=$((counter + 1))
done

# Merge TPB (Part X) files
while IFS= read -r file; do
    new_name=$(newname "$(basename "$file" .cbz)" "TPB \(Part [[:digit:]]+\)" TPB)
    extract_dir=$(realpath "$(dirname "$file")"/"$new_name")
    if [ ! -d "$extract_dir" ]; then
        mkdir -p "$extract_dir"
    fi
    unzip "$file" -d "$extract_dir"/"$(basename "$file" .cbz)"
    cd "$extract_dir" || exit
    zip -r "$(realpath "$(dirname "$file")")"/"$new_name"\.cbz ./
    trash "$file"
    trash "$extract_dir"/"$(basename "$file" .cbz)"
done < <(fd "Part \d+" --absolute-path -tf -s "${root_directories[@]}")

webtoon_mangas=(
    "Solo Leveling: Ragnarok"
    "Solo Leveling"
    "All Saints Street"
    "God of Blackfield"
    "The Non-Ability Fighter"
    "Red Storm"
    "Hardcore Leveling Warrior"
)

manga_dir=/srv/pool/multimedia/media/Library/manga/manga
webtoons_dir=/srv/pool/multimedia/media/Library/manga/webtoons
errors_dir=/srv/pool/multimedia/media/Library/manga/errors
for webtoon_manga in "${webtoon_mangas[@]}"; do
    if [ ! -d "$webtoons_dir/$webtoon_manga" ]; then
        fd "$webtoon_manga" -td --max-depth 1 -s \
            "$manga_dir" -x mv -n {} "$webtoons_dir"/
    else
        fd "$webtoon_manga" -tf --min-depth 2 -s \
            "$manga_dir" -e cbz -x mv -n {} "$webtoons_dir/$webtoon_manga"
    fi
done

if [ ! -d "$errors_dir" ]; then
    mkdir -p "$errors_dir"
fi

for directory in "${root_directories[@]}"; do
    fd . -td --min-depth 2 -s \
        "$directory" -x mv -n {} "$errors_dir/{/}"
done

fd . --absolute-path -tf -td "${root_directories[@]}" -x chown jawz:kavita {}
fd . --absolute-path -tf "${root_directories[@]}" -x chmod 664 {}
fd . --absolute-path -td "${root_directories[@]}" -x chmod 775 {}

fd . --absolute-path -td -te "${root_directories[@]}" -x rmdir {}
