#!/bin/bash

UUID=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)

yt-dlp "$1" --format bestaudio -o "(%(channel)s) %(title)s ($UUID)" --limit-rate 2.5M

FILENAME=$(ls | grep " ($UUID)" | head -n 1)
CURRENT=""

if [ $# -le 1 ]; then
    NAME="(..) $FILENAME.mp3"
    CURRENT="$NAME"

    ffmpeg -i "$FILENAME" -q:a 0 -map a "$NAME" && rm "$FILENAME"
else
    NAME="$2.mp3"
    CURRENT="$NAME"

    ffmpeg -i "$FILENAME" -q:a 0 -map a "$NAME" && rm "$FILENAME"
fi

if [ $# -gt 2 ]; then
    ffmpeg -ss "$3" -i "$CURRENT" "(...) $CURRENT"
    rm "$CURRENT" && mv "(...) $CURRENT" "$CURRENT"
fi

if [ $# -le 1 ]; then
    FINAL=$(echo "$CURRENT" | sed "s/""(..) ""/""""/")
    FINAL=$(echo "$FINAL" | sed "s/"" ($UUID)""/""""/")

    mv "$CURRENT" "$FINAL"
fi
