#!/bin/bash
#
# For bash aficionados :

# example of a possible implementation of siril scripting directly in bash :
#   all is included in a single bash script, siril commands are
#   executed as a "here document" (<<ENDSIRIL); this makes it easier
#   to manage than a script modifying a template-script to produce
#   a siril scipt then execute this script with siril. 
#   This is made possible by the '-s -' option passed to siril that
#   makes siril takes command from stdin
#
# this is just an example, it is not easy to used it out of the box,
# it is user friendly to me, but most probably to me alone :))
#
# But the main idea to retain is the inline inclusion of siril commands.
#
#
# exemple possible d'implémentation bash avec commandes siril "inline" :
#   avantage : tout est dans un seul script bash, les bash siril sont
#   executes en "here-document", grâce a l'appel de siril avec -c qui
#   prend les commandes sur l'entree standard
#
# On traite les fichiers qui sont dans le répertoire courant.
# 
#  S'il y a des Darks*.fits sous astrolab, c'est qu'ils n'ont pas encore été traités
#  donc on archive le master-dark courant présent sous astrolab/ dans archives/ en le
# renommant avec sa date de création
#
# fm, dulle@free.fr
#
version="0.99.9-6c61cd1e"
version=$(siril --version |awk '{print $2}')
ext="fits"

must_build(){
    #
    # 1st arg is the name of the band (dark, bias, flat, ...)
    # 2nd arg is the root name of the components (Dark*, Bias*, Flat*,....)
    #
    #
    mastername="master-$1.fits"
    crootname=$2

    if ! test -s "$mastername"; then
        buildmaster=0
    else
        #
        # Date d'observation du dernier master-dark :
        echo "#   Date de fabrication du dernier master $1 ($mastername) :">&2
        #

        read datemaster <<<$(fitsheader -k DATE $mastername |grep -v \# |awk -F= '{print $2}'|sed "s@/.*@@; s/'//g; s/\s*//g")
        read unixdatemaster<<<$(date +"%s" -d $datemaster)
        echo "#        $datemaster ($unixdatemaster)">&2
        read lastcomp <<<$(/bin/ls -tr "$crootname"*fits |tail -1)
        read datelastcomp <<<$(fitsheader -k DATE $lastcomp |grep -v \# |awk -F= '{print $2}'|sed "s@/.*@@; s/'//g; s/\s*//g")
        read unixdatelastcomp<<<$(date +"%s" -d $datelastcomp)
        echo "#">&2
        echo "#   Date d'acquisition du dernier Dark ($lastcomp) :">&2
        echo "#        $datelastcomp ($unixdatelastcomp)">&2
        if [ $unixdatelastcomp -gt $unixdatemaster ]; then
            echo "#     archive de l'ancien master-$1 et fabrication du nouveau master-$1">&2
            archmastername="master-$1-$datemaster.fits"
            mkdir -p archives
            echo "#     Archivage master-$1 : ">&2
            echo "#       mv $mastername archives/$archmastername">&2
            mv "$mastername" "archives/$archmastername"
            buildmaster=0
        else 
            echo "# $mastername est à jour">&2
            buildmaster=1
        fi
    fi
    return $buildmaster
}

build_bias(){
    banner bias

    build=bias
    root=Bias
    if must_build $build $root; then
        echo "#     Creation master-$build (siril) : "
        read seqname <<<$(/bin/ls -tr "$root"*fits |tail -1 | sed 's/[0-9]*.fits//') 
        echo $seqname

        /usr/local/bin/siril -i /home/fmeyer/.siril/siril.cfg -s - <<ENDSIRIL
requires  $version
setext $ext
stack $seqname med -nonorm -out=master-$build.fits
close
ENDSIRIL
    fi
}


build_dark(){
    banner dark

    build=dark
    root=Dark
    #if must_build $build $root; then
    if true; then
        echo "#     Creation master-$build (siril) : "
        read seqname <<<$(/bin/ls -tr "$root"*fits |tail -1 | sed 's/[0-9]*.fits//') 
        echo $seqname

        /usr/local/bin/siril -i /home/fmeyer/.siril/siril.cfg -s - <<ENDSIRIL
requires  $version
setext $ext
stack $seqname med -nonorm -out=master-$build.fits
close
ENDSIRIL
    fi
}

build_flat(){
    banner flats
    build=flat
    root=Flat
    if must_build $build $root; then
        echo "#     Creation master-$build (siril) : "
        read seqname <<<$(/bin/ls -tr "$root"*fits |tail -1 | sed 's/[0-9]*.fits//')
    /usr/local/bin/siril -i /home/fmeyer/.siril/siril.cfg -s - <<ENDSIRIL
    requires $version
    setext $ext
    preprocess $seqname -bias=master-bias
    stack pp_$seqname rej 3 3 -norm=mul -out=master-$build.fits
    close
ENDSIRIL
    fi
}

build_light(){
    banner lights
    echo obands ${obands[@]}
    let end=${#obands[@]}-1
    for index in $(seq 0 $end); do
        echo index $index
        root=${obands[$index]}
        build=$root
        if must_build $build $root; then
            echo "#     Creation master-$build (siril) : "
            read seqname <<<$(/bin/ls -tr "$root"*fits |tail -1 | sed 's/[0-9]*.fits//')
            /usr/local/bin/siril -i /home/fmeyer/.siril/siril.cfg -s - <<ENDSIRIL
requires  $version
setext $ext
preprocess $seqname -dark=master-dark -flat=master-flat
register pp_$seqname -norot
stack pp_$seqname sum -nonorm -out=master-$build.fits
close
ENDSIRIL
        fi
    done
}


# read date <<<$(fitsgetext -i master-dark.fits -o- -H -e DATE-OBS|sed s/\'//g) 
declare -a obands 
declare buildmaster
#
set -- `getopt "bdfla" "$@"`
# Sets positional parameters to command-line arguments.
while [ ! -z "$1" ]
do
  case "$1" in
    -b) build_bias
    shift;;
    -d) build_dark
    shift;;
    -f) build_flat
    shift;;
    -l) dolight=1
    shift;;
    -a) doall=1
        shift;;
     *) break;;
  esac
  shift
done
shift

if ! test -z "$1"; then
    while [ ! -z "$1" ]; do
        obands+=("$object$1")
        shift
    done
    for object in $obands; do
        banner $object 
        echo "# Processing bands : ${obands[*]}"
        build_light
    done
    cwd=$(pwd)
    wd="/home/fmeyer/astrolab"
    wd=$cwd
    cd $wd
fi

#
#
#
#
# retour maison 
#
cd $cwd
