#! /usr/bin/env nix-shell
#! nix-shell -i fish -p fish


set d_parent '/srv/disk2/scrapping/JawZ'
set d_gdl 'gallery-dl'
set d_gdl_filtered 'organized'

function _get_parent
    dirname (dirname $argv[1])
end
function _replace_path
    string replace $argv[1] $argv[2] $argv[3]
end

function _mv_files -a d
    for f in (find $d -type f)
        set f_name (basename $f)

        # Search for video files
        if test (string match -r "\.mp4|\.webm\$" $f_name)
            set f_dest (dirname $f)/Videos/(basename $f)
            # Loop until the parent directory isn't named Videos|mp4
            while test (string match -r "Videos|mp4" (basename (_get_parent $f_dest)))
                set f_dest (_get_parent $f_dest)/(basename $f_dest)
            end
            # Place videos in their own subdirectory
            set f_dest (_replace_path $d_gdl $d_gdl_filtered $f_dest)
        else # Not a video file
            set f_dest (_replace_path $d_gdl $d_gdl_filtered $f)
            echo $f_dest
        end

        set d_dest (dirname $f_dest)
        # Strip dirname for logging
        set d_name (string replace $d_parent "" $d_dest)
        # Check if destination exists
        if test ! -e $d_dest
            echo (set_color green)$d_name(set_color normal) \
                "Doesn't exist, creating..."
            mkdir -p $d_dest
        end

        # If destination exists, and basename isn't duplicated
        if test \( -e $d_dest \) -a \( (basename $f) = (basename $f_dest) \)
            echo "Moving the file" (set_color green)$f_name(set_color normal) \
                into (set_color green)$d_name(set_color normal)
            echo "Original path:"
            echo (set_color brblue)$f(set_color normal)
            echo "New path:"
            echo (set_color brblue)$f_dest | grep -F "$d_name"
            echo (set_color yellow)__________________________________(set_color normal)
            # Move files
            mv $f $f_dest
        end
    end
end

# TEST IF THE SCRIPT RAN WITH ARGUMENTS
if test -z "$argv[1]"
    echo "Please drag a few directories!"
    # _mv_files $d_gdl false
end
if test -n "$argv[1]"
    for d in $argv
        _mv_files $d true
    end
end
