#!/usr/bin/env bash

# HSC Analysis Pipeline
# Copyright (C) 2015-2018  HSC Data Analysis Software Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


# Description
# create-rootdir.sh ROOTDIR [REFDIR] [YSTRAYLIGHTDIR]
# create-rootdir.sh ROOTDIR [YSTRAYLIGHTDIR] [REFDIR]
#
# This script prepares a root directory for data analysis. It is not "/" but
# is a directory where input FITS files and output products will be saved.
#
# Usually, you should call this script with three arguments: ROOTDIR, REFDIR,
# and YSTRAYLIGHTDIR.
#
# ROOTDIR is the root directory for data analysis explained above.
#
# REFDIR is a directory that contains a reference catalog for photometric and
# astrometric calibration. "REFDIR/config.py" must exist because this script
# checks for it to confirm you have given a correct path.
#
# YSTRAYLIGHTDIR is a directory that contains y-band straylight data.
# "YSTRAYLIGHTDIR/ybackground-049.fits" must exist because this script checks
# for it to confirm you have given a correct path.
#
# If REFDIR or YSTRAYLIGHTDIR is not specified, it will not be set in ROOTDIR.
# To set one afterwards, run this script again with a valid REFDIR or
# YSTRAYLIGHTDIR.
# End Description

startup()
(
  help=false

  if [[ $# -eq 0 ]]
  then
    help=true
  else
    for i in "$@"
    do
      if  [[ "$i" = "-h" ]] ||
          [[ "$i" = "--h" ]] ||
          [[ "$i" = "--he" ]] ||
          [[ "$i" = "--hel" ]] ||
          [[ "$i" = "--help" ]]
      then
        help=true
        break
      fi
    done
  fi

  if $help
  then
    cat "$0" | sed -n '/^# Description/,/^# End Description/ { s/^\(# \|#\)// ; p }' |
      tail -n+2 | head -n-1
    exit 0
  fi

  if [[ $# -ge 4 ]]
  then
    echo "Too many arguments. See $(basename "$0") --help."
    exit 1
  fi

  main "$@"
)

main()
(
  set -e

  rootdir="$1"
  calibdir="${rootdir}"/CALIB

  if [[ -z "${rootdir}" ]]
  then
    echo "Specify the root directory for analysis." >&2
    exit 1
  fi

  shift

  refdir=""
  ystraylightdir=""

  for arg in "$@"
  do
    if check_refdir "${arg}"
    then
      if [[ -z "${refdir}" ]]
      then
        refdir="${arg}"
      else
        echo "error: Two or more reference directories were specified." >&2
        exit 1
      fi
    elif check_ystraylightdir "${arg}"
    then
      if [[ -z "${ystraylightdir}" ]]
      then
        ystraylightdir="${arg}"
      else
        echo "error: Two or more y-band straylight directories were specified." >&2
        exit 1
      fi
    elif [[ -n "${arg}" ]]
    then
      echo "error: This script cannot determine the kind of files in '${arg}'." >&2
      exit 1
    fi
  done

  if [[ -z "$OBS_SUBARU_DIR" ]]
  then
    dirs=("$(dirname "$(dirname "$0")")"/*/stack/miniconda*/*/obs_subaru/*/hsc)
    if  [[ ${#dirs[@]} -ne 1 ]] ||
        [[ ! -d "${dirs[0]}" ]]
    then
      echo '$OBS_SUBARU_DIR is not set and we failed in guessing it.'
      echo 'Set up the pipeline first, and run this script again.'
      exit 1
    fi

    pushd "$(dirname "${dirs[0]}")" > /dev/null
    OBS_SUBARU_DIR="$PWD"
    popd > /dev/null
  fi

  emplace_rootdir "${rootdir}"
  emplace_bfkernel "${OBS_SUBARU_DIR}" "${calibdir}"
  emplace_ref "${refdir}" "${rootdir}"
  emplace_ystraylight "${ystraylightdir}" "${calibdir}"
)

check_refdir()
(
  set -e
  dir="$1"

  if  [[ -n "${dir}" ]] &&
      [[ -e "${dir}"/config.py ]]
  then
    exit 0
  else
    exit 1
  fi
)

emplace_ref()
(
  set -e
  dir="$1"
  rootdir="$2"

  if  [[ -n "${dir}" ]] &&
      [[ ! -e "${rootdir}"/ref_cats/"$(basename "${dir}")" ]]
  then
    pushd "${dir}" > /dev/null
    dir="$PWD"
    popd > /dev/null

    mkdir -p "${rootdir}"/ref_cats
    ln -s "${dir}" "${rootdir}"/ref_cats/
  fi
)

check_ystraylightdir()
(
  set -e
  dir="$1"

  if  [[ -n "${dir}" ]] &&
      [[ -e "${dir}"/ybackground-049.fits ]]
  then
    exit 0
  else
    exit 1
  fi
)

emplace_ystraylight()
(
  set -e
  dir="$1"
  calibdir="$2"

  if  [[ -n "${dir}" ]] &&
      [[ ! -e "${calibdir}"/STRAY_LIGHT ]]
  then
    pushd "${dir}" > /dev/null
    dir="$PWD"
    popd > /dev/null

    mkdir -p "${calibdir}"
    # force-remove because "${calibdir}"/STRAY_LIGHT may be a broken link
    rm -f "${calibdir}"/STRAY_LIGHT
    ln -s "${dir}" "${calibdir}"/STRAY_LIGHT
  fi
)

emplace_bfkernel()
(
  set -e
  OBS_SUBARU_DIR="$1"
  calibdir="$2"

  if [[ ! -e "${calibdir}"/BFKERNEL/brighter_fatter_kernel.pkl ]]
  then
    mkdir -p "${calibdir}"/BFKERNEL
    ln -s "${OBS_SUBARU_DIR}"/hsc/brighter_fatter_kernel.pkl "${calibdir}"/BFKERNEL/
  fi
)

emplace_rootdir()
(
  set -e
  rootdir="$1"

  mkdir -p "${rootdir}"

  if [[ ! -e "${rootdir}/_mapper" ]]
  then
    echo 'lsst.obs.hsc.HscMapper' > "${rootdir}/_mapper"
  fi
)

startup "$@"
