あれ、chdir の有効範囲って local だったっけ?
そもそも1回目の
chdir "./$dirname";
でもし成功して temp/hoge/ になっちゃった場合、2回目はそこから chdir だから temp/hoge/fuga/ とかなんじゃねの?