#property strict
#property version "1.40"
#property script_show_inputs
#property description "Manual restart of a BADZO copier group after emergency closing"
input string StateFile="BADZO_MASTER_STATE.csv";

void OnStart()
  {
   string path=StateFile+".emergency.pause";
   if(!FileIsExist(path,FILE_COMMON)) {Print("BADZO: no emergency pause for this group.");return;}
   int answer=MessageBox("Ponovo ukljuciti BADZO copier za ovu StateFile grupu?\n\nPrvo provjeri SVE racune i pending naloge. Master pozicije ce se ponovo kopirati.","BADZO - nastavak kopiranja",MB_YESNO|MB_ICONQUESTION);
   if(answer!=IDYES) return;
   // Acquire only after the dialog: an open dialog must never block Emergency.
   int lock=FileOpen(path+".lock",FILE_READ|FILE_WRITE|FILE_BIN|FILE_COMMON);
   if(lock==INVALID_HANDLE) {Print("BADZO: another operation is active. Try again.");return;}
   int file=FileOpen(path,FILE_READ|FILE_CSV|FILE_COMMON|FILE_ANSI|FILE_SHARE_READ,';');
   if(file==INVALID_HANDLE) {FileClose(lock);Print("BADZO: cannot read pause file.");return;}
   string header=FileReadString(file);
   datetime until=(datetime)StringToInteger(FileReadString(file));FileClose(file);
   if(header!="BZE1" || until<=0) {FileClose(lock);Print("BADZO: invalid pause file.");return;}
   if(TimeGMT()<until) {FileClose(lock);Print("BADZO: wait ",(long)(until-TimeGMT())," seconds.");return;}
   if(PositionsTotal()>0 || OrdersTotal()>0) {FileClose(lock);Print("BADZO: check open positions and pending orders on all accounts first.");return;}
   bool removed=FileDelete(path,FILE_COMMON);
   if(removed) FileDelete(path+".resumed",FILE_COMMON);
   FileClose(lock);
   if(removed) Print("BADZO COPIER RESUMED: ",StateFile);
   else Print("BADZO: pause could not be removed. Error ",GetLastError());
  }
