#! /usr/bin/env nix-shell
#! nix-shell -i bash -p bash trashy fd ripgrep file jq curl

directories=("$HOME/Pictures/Unorganized/" "$HOME/Downloads/" "$HOME/Downloads/cache")
screenshots_dir=$HOME/Pictures/Screenshots/
photos_dir=$HOME/Pictures/Photos/camera/

replace_extension() {
    local file_basename
    file_basename=$(basename "$1")
    echo "${file_basename%.*}.$2"
}

generate_random_number() {
    local min=0
    local max=9999999999
    printf "%010d\n" $((min + RANDOM % max))
}

test_name() {
    local random_number
    random_number=$(generate_random_number)
    while (($(fd "$random_number"* "$HOME/Pictures/" "$HOME/Downloads/" -tf | wc -l) > 0)); do
        echo "Conflicts found, generating a new filename"
        random_number=$(generate_random_number)
        echo "$random_number"
    done
    echo "$random_number"
}

while IFS= read -r file; do
    regex_str='source|tenor|media|duckduckgo\.com|giphy|'
    regex_str+='(?<!app)image|^download|unknown|zoom|'
    regex_str+='new_canvas|untitled|drawpile|OIG|'
    regex_str+='imgpsh_|Dropped Image'
    if ! basename "$file" | rg --pcre2 -q "$regex_str"; then
        continue
    fi

    new_name=$(test_name)
    echo renaming
    echo "$file"
    echo into
    echo "$(dirname "$file")"/"$new_name"
    echo ---------------
    command mv -n "$(dirname "$file")"/{"$(basename "$file")","$new_name"}
    if ! basename "$file" | rg -q 'Screenshot_\d{8}'; then
        continue
    fi
    echo "moving screenshot $file into $screenshots_dir"
    command mv -n "$file" "$screenshots_dir"
done < <(fd . "${directories[@]}" -d 1 -tf --absolute-path)

classify_directories=("$screenshots_dir" "$photos_dir")
if (($(fd . "${classify_directories[@]}" -tf -d 1 | wc -l) > 0)); then
    while IFS= read -r file; do
        date=$(stat -c "%y" "$file" | rg -o "\d{4}-\d{2}-\d{2}")
        year=$(echo "$date" | rg -o "\d{4}")
        month=$(echo "$date" | rg -o "\d{4}-\d{2}" | rg -o --pcre2 "(?<=-)\d{2}")
        parent_dir=$(dirname "$(realpath "$file")")
        dest_dir=$(realpath "$parent_dir")/$year/$month
        echo "Moving screenshot $(basename "$file") into $dest_dir"
        mkdir -vp "$dest_dir"
        command mv -n "$file" "$dest_dir/"
    done < <(fd . "${classify_directories[@]}" --absolute-path -tf -d 1)
fi

# Where steam screenshots are stored, may need to replace with ur ID
dir_steam=$XDG_DATA_HOME/Steam/userdata/107446271/760/remote
cache_file="$dir_steam/game_cache"
if ! [[ -f $cache_file ]]; then
    echo "creating games database"
    touch "$cache_file"
fi

fetch_game_name() {
    local game_id
    game_id=$1

    local cache_entry
    cache_entry=$(grep "^$game_id," "$cache_file")
    if [ -n "$cache_entry" ]; then
        echo "$cache_entry" | cut -d ',' -f2-
    else
        local response
        response=$(curl -s "https://store.steampowered.com/api/appdetails?appids=${game_id}")
        local game_name
        game_name=$(echo "$response" | jq -r ".\"${game_id}\".data.name")
        if [ -n "$game_name" ]; then
            echo "$game_id,$game_name" >>"$cache_file"
            echo "$game_name"
        else
            echo "ERROR"
        fi
    fi
}

while IFS= read -r game_dir; do
    game_id=$(basename "$game_dir")
    game_name=$(fetch_game_name "$game_id")
    if [ "$game_name" == "ERROR" ]; then
        continue
    fi
    # Modify this to store your screenshots somewhere else
    dir_dest=$(realpath "$screenshots_dir/Games")/"$game_name"
    dir_game=$(realpath "$dir_steam")/"$game_id"/screenshots
    # If there are not screenshots currently stored, why bother lol
    if ! [[ -d $dir_game ]]; then
        continue
    fi
    # If screenshots exist however...
    if ! (($(fd . "$dir_game" -d 1 -tf | wc -l) > 0)); then
        continue
    fi
    # Create destination directory
    mkdir -vp "$dir_dest"
    fd . "$dir_game" -d 1 -tf -x cp -n {} "$dir_dest"/
done < <(fd . "$dir_steam" -td --max-depth 1 --absolute-path)

cyberpunk_dir=$HOME/Games/gog/cyberpunk-2077/drive_c/users/jawz/Pictures/"Cyberpunk 2077"
if [[ -d $cyberpunk_dir ]]; then
    while IFS= read -r file; do
        echo "Moving cyberpunk screenshots $(basename "$file")"
        command mv -n "$file" "$screenshots_dir/Games/Cyberpunk 2077/"
    done < <(fd . "$cyberpunk_dir" -tf)
fi

proton_dir=$HOME/.steam/steam/compatibilitytools.d
if [[ -d "$proton_dir" ]]; then
    while IFS= read -r proton_version; do
        proton_name=$(basename "$proton_version")
        if [ "$proton_name" == "LegacyRuntime" ]; then
            continue
        fi
        lutrisdir=$XDG_DATA_HOME/lutris/runners/wine/"$proton_name"
        if [ -d "$lutrisdir" ] && [ -L "$lutrisdir" ]; then
            continue
        fi
        echo "Symlink $lutrisdir doesn't exist, creating link..."
        ln -s "$(realpath "$proton_version")"/files "$lutrisdir"
    done < <(fd . "$proton_dir" -d 1 -td)
fi
fd . "$XDG_DATA_HOME/lutris/runners/wine" -d1 -tl -Lx trash {}

while IFS= read -r file; do
    ext=$(file --mime-type "$file" | rg -o '\w+$')
    correct_ext=${ext,,}
    filename=$(basename -- "$file")
    current_ext="${filename##*.}"
    filename="${filename%.*}"
    if ! echo "$correct_ext" | rg -q 'jpe|jpg|jpeg|png|gif|webp'; then
        continue
    fi
    if [ "$current_ext" == "$correct_ext" ]; then
        continue
    fi
    echo "The file $(basename "$file")" \
        "will be renamed, the proper extension is $correct_ext"
    new_name="$filename".$correct_ext
    dest_path="$(dirname "$file")/$new_name"

    if [ ! -e "$dest_path" ]; then
        mv "$file" "$dest_path"
        continue
    fi

    file_hash="$(sha256sum "$file" | gawk '{ print $1 }')"
    if echo "$file_hash $dest_path" | sha256sum -c --quiet; then
        echo "Deleting duplicate (same hash): $file"
        rm "$file"
    else
        echo "WARNING: $file and $dest_path have different content, skipping"
    fi
done < <(fd . "${directories[@]}" -d 1 -tf)

files_home_clean=(.pki HuionCore.pid DriverUI.pid huion.log)
for file in "${files_home_clean[@]}"; do
    file=$HOME/$file
    if [ ! -e "$file" ]; then
        continue
    fi
    rm -rf "$file"
done
