##########################################################################
##                                                                      ##
##  I N T E R S T E L L A R   C O N S O L E   Startup Script            ##
##                                                                      ##
##            Copyright (C) 2025- Misato Observatory, Wakayama, Japan   ##
##                                                                      ##
##  This software is available under the GPL (General Public License)   ##
##                                                                      ##
##########################################################################

#
#                             Block Diagram
#
# +-----------------+       ______________      +------------------+
# |                 |      /              |     |                  |
# | ISC Info Server | <-- | Config/Status | <-- |                  |
# |  (iscserv.tcl)  |     | of Stellarium |     |    Stellarium    |
# |                 |     |_______________|     |                  |
# +-----------------+    %HOMEDRIVE%%HOMEPATH%/ |                  |
#          |             AppData/Roaming/       +------------------+
#          |             Stellarium               |  A      |
#          |                                Status|  |      +------> Projector
#          |Results of Scripts         (port:8090)|  |
#          |(port:8091)                           |  |Script(port:8090)
#          |                                      V  |
#          |         +--------------------------------------+
#          +-------> |                                      ||
#     _________      |              ISC GUIs                ||
#    /         |     | (misato-gui.tcl, date-gui.tcl, etc.) || -----> Display
#   |  Config  | --> |                                      ||
#   |  of ISC  |     |______________________________________||
#   |__________|       --------------------------------------+
#   %PROGRAMFILES%/
#   Stellarium/scripts/
#   interstellar-console
#

####################################################################

#
# Arguments
#
#  -gui-only
#    Setup GUI only
#
#  -navi
#    Navigation mode
#
#  -dome
#    Dome mode
#
#  -kill
#    Stop all processes of Stellarium and ISC programs
#
#  -rescue
#    Rescure mode
#
#  -no-fullscreen
#    A flag to disable fullscreen in dome mode.
#    Set this arg if the Stellarium window crashes in Dome mode.
#
#  -black-mask width,height,x,y
#    Create a square black mask on the screen
#

####################################################################


#
# Procedures for handling OS-dependent processes.
#
source system-proc.tcl


####################################################################

#
# Return number of files
#
proc count_files { arg_in } {

  set filelist [glob -nocomplain "$arg_in"]

  return [llength $filelist]

}

####################################################################


set stellarium_executable_file [get_stellarium_executable_file]

set stellarium_io_directory [get_stellarium_io_directory]

set version_str ""
if { [catch {open "VERSION.txt" r} fid] } {
  # do nothing
} else {
  if { [gets $fid line] >= 0 } {
    set v [string trim $line]
    set version_str "version $v"
  }
  catch {close $fid}
}

puts "//"
puts "// INTERSTELLAR CONSOLE $version_str startup script (tcl)"

set mode "-"
set flag_gui_only 0
set rescue_arg "-"
set flag_no_fullscreen 0
set arg_blackmask ""

# Setup args_all with parsing additional arguments in exec-args.txt

array set args_all {}
set cnt 0
for {set i 0} {$i < $argc} {incr i} {
  set args_all($cnt) [lindex $argv $i]
  incr cnt
}

if { [catch {open "exec-args.txt" r} fid] } {
  # do nothing
} else {
  while { [gets $fid line] >= 0 } {
    set arg [string trim $line]
    # check args or skip comments
    if { [string length $arg] != 0 && [string index $arg 0] ne "#" } {
      set lst [split $arg " "]
      set len_lst [llength $lst]
      for {set i 0} {$i < $len_lst} {incr i} {
        set s [string trim [lindex $lst $i]]
        if { $s ne "" } {
          set args_all($cnt) $s
          incr cnt
        }
      }
    }
  }
  catch {close $fid}
}
set len_args_all $cnt

# Parsing arguments

for {set i 0} {$i < $len_args_all} {incr i} {
  set arg $args_all($i)
  if { $arg eq "-gui-only" } {
    set flag_gui_only 1
  } elseif { $arg eq "-navi" } {
    set mode "navigation"
  } elseif { $arg eq "-dome" } {
    set mode "dome"
  } elseif { $arg eq "-kill" } {
    set mode "kill"
  } elseif { $arg eq "-rescue" } {
    set rescue_arg "-rescue"
  } elseif { $arg eq "-no-fullscreen" } {
    set flag_no_fullscreen 1
  } elseif { $arg eq "-black-mask" } {
    set next_i $i
    incr next_i
    if { $next_i < $len_args_all } {
      incr i
      set arg_blackmask $args_all($i)
    }
  }
}

puts "// Mode: $mode"
puts "//"

set v [info patchlevel]
puts "Tcl version is $v."

puts "Number of files in [pwd] :"
set n_exe [count_files "*.exe"]
set n_txt [count_files "*.txt"]
set n_tcl [count_files "*.tcl"]
set n_ssc [count_files "*.ssc"]
set n_inc [count_files "*.inc"]
set n_images [count_files "images/*"]
set n_media [count_files "media/*"]
puts "(*.exe, *.txt, *.tcl, *.ssc, *.inc) = ($n_exe, $n_txt, $n_tcl, $n_ssc, $n_inc)"
puts "(images/*, media/*)                 = ($n_images, $n_media)"

# Cleanup...

catch {exec taskkill /F /im wish.exe 2>@1} ret

set date_monitor_pid_file "$stellarium_io_directory/_tmp_date-monitor_pid.isc.txt"
file delete -force $date_monitor_pid_file

if { $flag_gui_only == 1 } {

  # GUI only
  if { $mode eq "kill" } {
    exit 0
  }
  after 1000

} else {

  set this_pid [pid]

  catch {exec taskkill /F /im stellarium.exe 2>@1} ret
  catch {exec taskkill /F /im tclsh.exe /fi "PID ne $this_pid" 2>@1} ret

  after 1000

  if { $mode eq "kill" } {
    exit 0
  }

  puts "Confirm wish ..."

  set wish_path [auto_execok wish]
  if { $wish_path eq "" } {
    puts stderr "/////////////////////////////////"
    puts stderr "// ERROR: Tk is not installed! //"
    puts stderr "/////////////////////////////////"
    after 3000
    exit 1
  }

  puts "Prepare config.ini ..."

  set path_of_ini "$stellarium_io_directory/config.ini"

  if { [file exists $path_of_ini] == 0 } {

    exec -ignorestderr "$stellarium_executable_file" --full-screen no &

    while { 1 } {
      if { [file exists $path_of_ini] != 0 } {
        after 5000
        catch {exec taskkill /F /im stellarium.exe 2>@1} ret
        break
      }
      after 1000
    }
  }

  set ret [exec tclsh -encoding $TCLSRC_ENCODING isc-prepare.tcl]
  puts "$ret"

  puts "Exec ISC Info Server ..."

  exec -ignorestderr cmd.exe /c start /min tclsh.exe -encoding $TCLSRC_ENCODING iscserv.tcl 8091 &

  while { 1 } {

    # Check that ISC Info Server has finished booting
    set status [catch {exec curl -s -G http://localhost:8091/} ret]
    if { $status == 0 } {
      puts $ret
      break
    }

    after 1000

  }

  puts "Exec ISC Scheduler ..."

  exec -ignorestderr cmd.exe /c start /min tclsh.exe -encoding $TCLSRC_ENCODING isc-scheduler.tcl &

  puts "Exec Stellarium ..."

  if { $mode eq "dome" } {
    if { $flag_no_fullscreen != 0 } {
      puts "Info: flag_no_fullscreen is enabled."
      exec -ignorestderr "$stellarium_executable_file" --full-screen no &
    } else {
      exec -ignorestderr "$stellarium_executable_file" --full-screen yes &
    }
  } else {
    exec -ignorestderr "$stellarium_executable_file" --full-screen no &
  }

  puts "Waiting for Stellarium to finish booting ..."

  while { 1 } {

    # Check that Stellarium has finished booting
    set status [catch {exec curl -s -G http://localhost:8090/api/main/status} ret]
    if { $status == 0 } {
      break
    }

    after 1000

  }

  if { $mode eq "dome" && $flag_no_fullscreen != 0 } {
    after 2000
    puts "Info: Maxmize window of stellarium.exe"
    exec -ignorestderr ./nircmd.exe win max process stellarium.exe
    # Note: This does not work correctly...
    # curl -d "code=core.setWindowSize(9999,9999)" http://localhost:8090/api/scripts/direct
  }

  if { $arg_blackmask ne "" } {
    puts "Info: Setup black-mask"
    exec wish black-mask.tcl $arg_blackmask &
  }

}

puts "Exec GUI"

if { $flag_gui_only == 1 } {
  # Check that Stellarium has finished booting
  set status [catch {exec curl -s -G http://localhost:8090/api/main/status} ret]
  if { $status != 0 } {
    puts stderr "/////////////////////////////////////////"
    puts stderr "// ERROR: No response from Stellarium! //"
    puts stderr "/////////////////////////////////////////"
    after 3000
    exit 1
  }
  set init_arg "-"
} else {
  set init_arg "-init"
}

if { $mode eq "navigation" } {
  exec wish -encoding $TCLSRC_ENCODING misato-gui.tcl -host -navi $init_arg $rescue_arg &
} elseif { $mode eq "dome" } {
  exec wish -encoding $TCLSRC_ENCODING misato-gui.tcl -host -dome $init_arg $rescue_arg &
} else {
  exec wish -encoding $TCLSRC_ENCODING misato-gui.tcl -host $init_arg $rescue_arg &
}

