#!/usr/bin/bash

###########################################################################
# Copyright (C) 2020, 2021, 2022 IoT.bzh                                  #
#                                                                         #
# Authors:  Salma   Raiss   <salma.raiss@iot.bzh>                         #
#                                                                         #
# Licensed under the Apache License, Version 2.0 (the "License");         #
# you may not use this file except in compliance with the License.        #
# You may obtain a copy of the License at                                 #
#                                                                         #
#     http://www.apache.org/licenses/LICENSE-2.0                          #
#                                                                         #
# Unless required by applicable law or agreed to in writing, software     #
# distributed under the License is distributed on an "AS IS" BASIS,       #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.#
# See the License for the specific language governing permissions and     #
# limitations under the License.                                          #
###########################################################################
#               Update module for redpesk payloads                        #
###########################################################################

set -e

shopt -s extglob

version=2
STATE="$1"
FILES="$2"
FILES_DIR="$FILES"/files/
FILES_IN_DIR="$FILES"/files/*
METADATA_FILE="$FILES_DIR"/metadata
TMP_RPMS_DIR="/tmp/updateRpms"
FILES_IN_DEST_DIR="$TMP_RPMS_DIR"/*
UPDATE_RPMS_TAR="$FILES"/files/update.tar

case "$STATE" in
   ArtifactInstall)
      source $METADATA_FILE
      # check update module version
      if [[ $VERSION -lt $version ]]; then
        >&2 echo "Error : Version mismatch. You need to upgrade your artifact generating script" | systemd-cat -p emerg
        exit 1
      fi
      if [[ "$PAYLOAD_TYPE" == "rpm-os" ]]; then
        echo "Payload is of RPM type"
        rpm --define='%_pkgverify_level all' -U -v --force $FILES_DIR/!(metadata)
        echo "RPM successfully installed!"
      elif [[ "$PAYLOAD_TYPE" == "rpm-dir" ]]; then
        echo "Payload is a directory tarball of RPMs"
        mkdir -p ${TMP_RPMS_DIR}
        tar -xf ${UPDATE_RPMS_TAR} -C ${TMP_RPMS_DIR}
        for file in $FILES_IN_DEST_DIR
        do
           echo "Analyzing file $file"
           filename="$(basename $file)"
           if [[ "${filename:0:6}" = "delta-" ]]
           then
               echo "File is of DRPM type"
               applydeltarpm -v $file /tmp/test.rpm
               dnf install /tmp/test.rpm -y
               rm /tmp/test.rpm
           else
               echo "File is of RPM type"
               dnf install $file -y
           fi
        done
        rm -r $TMP_RPMS_DIR
        echo "Successfully installed RPM directory tarball!"
      elif [[ "$PAYLOAD_TYPE" == "recovery-bin" ]]; then
        echo "Payload is a recovery binary"
        for file in $FILES_DIR/!(metadata)
        do
           chmod +x $file
           mount=false
           if ! grep -qs "/recovery" /proc/mounts; then
              # mount recovery partition
              mount=true
              echo "Mounting recovery partition... "
              mount /dev/sda3 /recovery
           fi
           # Check if old version is there
           if ls /recovery/*.run &>/dev/null ; then
               # Remove old installer
               echo "[WARNING] Another version of recovery-image-installer is already there!"
               echo "[WARNING] Removing the old version of recovery-image-installer! "
               rm /recovery/*.run
           fi
           # Copy the recovery script to where the recovery will pick it up
           echo "Copying recovery-image-installer to /recovery... "
           mv $file /recovery
           if $mount ; then
              # unmount recovery partition
              echo "Unmounting recovery partition... "
              umount /recovery
           fi
        done
        echo "Successfully installed recovery payload!"
      elif [[ "$PAYLOAD_TYPE" == "rpm-redpak" ]]; then
        echo "Payload is a redpak node RPM!"

        REDPAK_CONTAINER_RPM=$(basename "$FILES_DIR"/"$REDPAK_CONTAINER_NAME"*)

        >&2 echo "Installing redpak node rpm ..."
        dnf install "$FILES_DIR"/"$REDPAK_CONTAINER_RPM" -y

        >&2 echo "Updating package in node $REDPATH... "
        for file in $FILES_DIR/!(metadata|$REDPAK_CONTAINER_RPM)
        do
          chmod +755 $file
          cp -p $file $REDPATH/var/
          filename=$(basename $file)
          >&2 echo "Updating package $file in node $REDPATH..."
          yes | su - rp-owner -c "redwrap-dnf --redpath="$REDPATH" install $REDPATH/var/$filename" > /tmp/test
        done
        echo "Redpak node update was successful!"
      else
        >&2 echo "Failed : Unknown payload file type!"
        exit 2
      fi
esac
exit 0