#!/bin/tcsh

if ($#argv != 2) then
  echo "USAGE: mkwarps (filter) (test/commit)"
  echo " filter: i.00000 or z.00000"
  exit 2
endif

# the skycell list is generated within dvo:
#
# dvo: catdir /local/ipp/gpc1/tess/CFIS.V0/
# dvo: skyregion {8*15} {9*15} 38 40
# dvo: output skycells.txt
# dvo: imlist
# dvo: output stdout

set filter = "$1"

set Nlimit = 2
set Ncells = 2
if ("$2" == "commit") then
  set Nlimit = 1000000
  set Ncells = 1000000
endif

set level1 = "warps.$filter"
set wdirs1 = "webpages/$level1"
set pages1 = "$wdirs1/index.html"
mkdir -p $wdirs1
echo $pages1

# level 1 content:
echo "<html><head><body>" > $pages1

# remove the "head" bit when ready:
foreach skycell (`cat skycells.txt | awk '{print $2}' | head -n $Ncells`)

  # echo $skycell
  set level2 = $level1/$skycell
  set wdirs2 = "webpages/$level2"
  set pages2 = "$wdirs2/index.html"
  mkdir -p $wdirs2
  echo $pages2

  # level 1 content:
  echo "<a href=$skycell/index.html> $skycell </a><br>" >> $pages1

  # level 2 content:
  echo "<html><head><body>" > $pages2

  foreach path_base (`warptool -dbname gpc1 -warped -label UNIONS.DR2.20190430 -skycell_id $skycell -filter $filter -limit $Nlimit | grep path_base | awk '{print $3}'`)

    # echo $path_base
    set outbase = `basename $path_base`

    set level3 = $level2/$outbase
    set wdirs3 = "webpages/$level3"
    set pages3 = "$wdirs3/index.html"
    mkdir -p $wdirs3
    echo $pages3

    # level 2 content:
    echo "<a href=$outbase/index.html> $outbase </a><br>" >> $pages2

    # level 3 content:
    echo "<html><head><body>" > $pages3

    foreach ext (cmf fits mask.fits wt.fits psf)
      set nebname = $path_base.$ext
      set nebbase = `basename $nebname`
      set realname = `neb-locate -p $nebname`
      ln -s $realname $wdirs3/$nebbase
      echo "<a href=$nebbase> $nebbase </a><br>" >> $pages3
    end
    echo "</html></head></body>" >> $pages3
  end
  echo "</html></head></body>" >> $pages2
end

echo "</html></head></body>" >> $pages1
