FYI, I think you forgot some important quotes in your script. Try shellcheck?
> mkdir -p $(dirname "$2")
That'll handle whitespace in paths, but if you want it to handle all path characters, dirname and mkdir need "--" here too.