#!/bin/bash
#
# autodist launcher
# (c) 2021-2026 by Silvan Calarco <silvan.calarco@mambasoft.it>
#
. /etc/autodist/config
. /etc/autodist/autoport

# Disable icecc
export PATH=/usr/bin:$PATH

i=$1

[ "$i" ] || {
   echo "Usage: autodist-launcher autodist_conf"
   exit 1
}

PIDFILE=/run/autodist/autodist-launcher-${i}.pid
[ -e $PIDFILE ] && {
   PIDCHECK=`cat $PIDFILE`
   [ "$PIDCHECK" -a -e /proc/$PIDCHECK ] && {
      echo "autodist-launcher for configuration $i already running; exiting."
      exit 0
   }
}
echo $$ > $PIDFILE
trap "rm -f $PIDFILE; exit 1" SIGQUIT SIGINT SIGKILL SIGTERM

HOUR=`date +%H`
[ "`uname -m`" = "x86_64" ] && HOST_IS_X86_64=1

AUTODIST_PIDFILE=/run/autodist/autodist.pid
LOGFILE=/var/autodist/log/autodist.log
LASTLOGFILE=/var/autodist/log/autodist-last.log

if [ -e $AUTODIST_PIDFILE ]; then
  PIDCHECK=`cat $AUTODIST_PIDFILE`
  if [ "$PIDCHECK" -a -e /proc/$PIDCHECK ]; then
     echo "autodist already running; exiting."
     exit 0
  fi
fi

for r in ${AUTOPORT_REPOSITORIES[$i]}; do
   [ "${AUTOPORT_ARCH[$i]}" ] || continue
   [ "${AUTOPORT_DISABLE[$i]}" -a "${AUTOPORT_DISABLE[$i]}" != "0" ] && continue

   if [ "$HOST_IS_X86_64" -a "${AUTOPORT_ARCH[$i]}" != "x86_64" ]; then
      CMD_PREFIX=linux32
   else
      CMD_PREFIX=
   fi

   # TODO: parametrize DISTROMATIC_REPOSITORY and following log files
   DISTROMATIC_REPOSITORY=devel-future

   if [ "$LOCAL_REPS_BASE_DIR" == "" ]; then
      LOCAL_REPS_BASE_DIR=/var/autodist
      LOCAL_REPS_FETCH=1
   fi

   REPLOGFILE=$LOCAL_REPS_BASE_DIR/$r/autodist.log
   REPLASTLOGFILE=$LOCAL_REPS_BASE_DIR/$r/autodist-last.log

   if [ "${AUTOPORT_UPDATE[$i]}" ]; then

      if [ "${LOCAL_REPS_FETCH}" != "" ]; then
          echo "Fetching metadata files from base..."
          for f in legacy updates-conf.json; do
             su -l autodist -c "curl -f -L -s ${REPS_BASE_URL}/base/${f} -o ${LOCAL_REPS_BASE_DIR}/base/${f}"
          done

          echo "Fetching autoupdate folder from $r..."
          su -l autodist -c "rclone --config /dev/null \
             copy :webdav:/${r}/autoupdate \
             $LOCAL_REPS_BASE_DIR/${r}/autoupdate \
             --webdav-url ${REPS_BASE_URL}"
          if [ $? -ne 0 ]; then
             echo "ERROR $? returned by rclone for ${r}; skipping."
             continue
          fi
      fi

      autodist-upstream-updates -q -u -r $DISTROMATIC_REPOSITORY -o $r

      [ -e $LOGFILE ] && mv $LOGFILE $LASTLOGFILE
      su -l autodist -c "$CMD_PREFIX autodist -a --server $r" > $LOGFILE
      [ -e $REPLOGFILE ] && mv $REPLOGFILE $REPLASTLOGFILE
      cp $LOGFILE $REPLOGFILE
   fi
done
rm -f ${PIDFILE}
