Your script has no lay-out at all and is thus very difficult to read for human beings. I guess thaa even you can not see at aglance in your own script if every “if” has it’s “fi”, etc.
One normaly uses the TAB character to give structure to a program:
if somecondition ]]
then
dosomething
domore
else
dosemethingelse
fi
The shell normaly gives such an error as you got when it is at the end of the script and a construct is still unfinished (like the last “fi” missing in an “if”).
I advise you to create a good programmimg style and when you apply that to the script, I guess you will see the error yourself. When not, post the improved script here.