#!/bin/sh
#  $Id: sm_disaster,v 1.20 2013/08/02 09:32:22 kha Exp $
# ******************************************************************************
#  
#   Module    : sm_disaster
#   Copyright : (c) 2002 SEP AG D-883607 Holzkirchen
#   Project   : SESAM Backup Utility
#   Date      : 2025-05-12
# 
# ******************************************************************************
#
#  >>> This is a user-programmable procedure <<<
#
#  >>> Dies ist eine vom Benutzer programmierbare Prozedur <<<
#
# ******************************************************************************
# 
# Description :
#    This script is used to prepare a recovery of your SEP sesam Server in case of a disaster 
#    recovery and should ensure that in case of an unexpected failure you have access to the 
#    most recent self-backup of the SEP sesam Server.
#
#    This script is executed after a backup if the task name contains "DISASTER" or "SESAM" 
#    (e.g.  the backup task "SESAM_BACKUP" configured by default during a new installation
#    backup task "SESAM_BACKUP" configured by default).
#
#    A self-backup of the SEP sesam Server should contain the following files: all files in the 
#    SEP sesam main folder <SEP sesam home> and the files of the LIS directory 
#    <SEP sesam home>\var\lis> if these files are not stored in the SEP sesam main folder. In 
#    addition, the SEP sesam database should be included in the backup. This is guaranteed 
#    for the default task "SESAM_BACKUP".
#
#    This script sends an email containing all the necessary information for disaster recovery. 
#    It is strongly recommended to keep multiple copies of the sent files in different locations 
#    and ensure that they are available in case of a SEP sesam Server failure. For example, you 
#    may save them to other computers within your network or send them by email.
#
#    The email can only be sent by the SEP sesam Server if a mail account exists in SEP sesam 
#    for the user “sesam” (GUI menu: Configuration -> Email Settings -> New).
#
#    SEP sesam provides various information such as the data storage path or the tape label 
#    and, if applicable, the barcode of the medium used and a complete restore command to 
#    copy all files of the running backup back to their original locations.
#
#    These values are transferred as follows:
#
#         $1 = Media Label: {label}, Source: {backup source}, Barcode: {barcode}
#         oder
#         $1 = Datastore Path: {path of the datastore}
#         $2 = {sbc restore command}
#         $3 = {file name of the data store export or ini file}
#         oder
#         $3 = {cloud based sesam_dr_info.ini file} 
#
#    You can find more details about disaster recovery at
#    https://wiki.sep.de/wiki/index.php/SEP_sesam_Server_Disaster_Recovery_with_Bootstrap_DB_Export
#    and at
#    https://wiki.sep.de/wiki/index.php/SEP_sesam_Server_Cloud-Based_Disaster_Recovery
#    Pay attention to your SEP sesam version in the description.
#
#    This script can be customized to your needs by simply editing it.
#
# ******************************************************************************
#
# Beschreibung 
#    Dieses Skript dient der Vorbereitung einer Wiederherstellung Ihres SEP sesam Servers 
#    im Katastrophenfall (Disaster Recovery) und soll dafür sorgen, dass Sie im Falle eines 
#    unerwarteten Ausfalls Zugriff haben auf die jüngste Selbstsicherung des SEP sesam 
#    Servers.
#
#    Dieses Skript wird nach einer Sicherung aufgerufen, falls der Auftragsname
#    "DISASTER" oder "SESAM" beinhaltet (wie z.B. der bei einer Neuinstallation 
#    standardmäßig konfigurierte Sicherungsauftrag "SESAM_BACKUP").
#
#    In einer Selbstsicherung des SEP sesam Server sollten folgende Dateien enthalten 
#    sein: alle Dateien im SEP sesam Hauptordner <SEP sesam home> sowie die Dateien des 
#    LIS-Verzeichnis <SEP sesam home>\var\lis>, sofern diese Dateien nicht im SEP Sesam 
#    Hauptordner abgelegt sind. Ausserdem sollte die SEP sesam Datenbank in der Sicherung 
#    enthalten sein. Für den Standard-Auftrag „SESAM_BACKUP“ ist dies gewaehrleistet.
#
#    Durch dieses Skript wird eine Email geschickt, die alle noetigen Information für die 
#    Wiederherstellung im Katastrophenfall enthaelt. Es wird dringend empfohlen mehrere 
#    Kopien der verschickten Dateien an unterschiedlichen Orten aufzubewahren und sicher zu 
#    stellen dass sie im Falle eines SEP sesam Server Ausfalls verfuegbar sind. Die Dateien 
#    z.B. auf anderen Computer im Netzwerk gespeichert oder per E-Mail versandt werden.
#
#    Die Email kann vom SEP sesam Server nur verschickt werden, wenn ein Mailaccount im 
#    SEP sesam für den Benutzer "sesam" existiert (GUI Menue: Konfiguration -> E-Mail 
#    Einstellungen -> Neu)
#
#    SEP sesam stellt verschiedene Information wie den Datenspeicherpfad oder das 
#    Bandlabel und ggf. den Barcode des benutzten Mediums und einen vollstaendigen 
#    Ruecksicherungsbefehls bereit, um alle Dateien der gelaufenen Sicherung wieder an ihren 
#    urspruenglichen Plaetze zurueckzukopieren. 
#
#    Diese Werte werden wie folgt übergeben:
#
#         $1 = Media Label: {Bandlabel}, Source: {Sicherungsquelle}, Barcode: {Barcode}
#         oder
#         $1 = Datastore Path: {Pfad des Datenspeichers}
#         $2 = {sbc Ruecksicherungsbefehl}
#         $3 = {Dateiname des Datenbackexports}
#         oder
#         $3 = {Cloud basierte sesam_dr_info.ini Datei} 
# 
#    Naehere Details zum Thema Disaster Recovery finden Sie unter
#    https://wiki.sep.de/wiki/index.php/SEP_sesam_Server_Disaster_Recovery_with_Bootstrap_DB_Export
#    und unter
#    https://wiki.sep.de/wiki/index.php/SEP_sesam_Server_Cloud-Based_Disaster_Recovery
#    Achten Sie bei der Beschreibung auf Ihre passende SEP sesam Version.
#
#    Dieses Skript kann durch einfaches Editieren auf Ihre Beduerfnisse angepasst werden.
#
# ******************************************************************************
#
read_ini()
{
  . `grep -i '^sm_ini=' /etc/sesam2000.ini|cut -d"=" -f2` 2>/dev/null
}
read_ini
. ${gv_rw_ini}/sesam2000.profile > /dev/null 2>&1
VERSION=`echo ${version} | cut -d"," -f2` 2>/dev/null

attachment=$3
if [ -f "${attachment}" ]
then
   echo "${attachment} given by the user"
else
   attachment=`ls -tr ${gv_rw_db}/backup/sesam_bootstrap_db_* | tail -n1`
   iniSbcFile=`ls -tr ${gv_rw_db}/backup/sesam_ini_*.sbc | tail -n1`
fi

storageInfo=$1
restoreCmd=$2
disaster_tmp_file=${gv_rw_work}/disaster.tmp

# If the name of the attachment contains .ini then the method is cloud based otherwise it is bootstrap db based
if [[ "${attachment}" == *".ini" ]]
then
   if [ "$lang" = "de" ]
   then
# Deutsch:
cat <<EOF > ${disaster_tmp_file}
Im Katastrophenfall werden die Informationen aus den Dateien im Anhang benoetigt, um das
SEP sesam System wiederherzustellen. Diese Dateien sollten ausschliesslich fuer die Wiederherstellung
des SEP sesam Systems verwendet werden.
Das SBC-Archiv der Konfigurationsdateien (sesam.ini.{.}.sbc) enthaelt die oeffentlichen SSH-Schluesseldateien,
die fuer den Zugriff auf die RDS erforderlich sind.
Sie sollten diese E-Mail und den Anhang an einem sicheren Ort speichern.

VORGEHENSWEISE ZUR WIEDERHERSTELLUNG DES SEP SESAM SYSTEMS:

   1. Speichern Sie den Anhang (sesam_dr_info.ini Datei) aus dieser E-Mail auf dem System, das Sie fuer
      die SEP sesam Server Wiederherstellung verwenden.

   2. Führen Sie eine saubere Installation des SEP sesam Servers durch, um die erforderliche Umgebung für
      die Wiederherstellung der Serverkonfiguration und der Sicherungsdaten bereitzustellen

   3. Aktivieren Sie die globale Ausführung von SEP sesam Befehlen von einem Terminal oder einer
      Eingabeaufforderung (CMD), indem Sie ein SEP sesam Profil einrichten.
      Starten Sie die Wiederherstellung mit folgendem Befehl auf der Kommandozeile:
      sm_pysesam sesam_recover -f <Pfad zur sesam_dr_info.ini-Datei>
      Ersetzen Sie <Pfad zur sesam_dr_info.ini-Datei> mit dem Pfad zur in Schritt 1 gespeicherten Datei.

EOF
   else 
# English:
cat <<EOF > ${disaster_tmp_file}
In the event of disaster, the information from the files in the attachment is required to restore the SEP
sesam system. It should be used exclusively for SEP sesam system recovery.
The SBC archive of the configuration files (sesam.ini.{.}.sbc) contains the public SSH key files,
required for access to the RDS.
You should save this email and the attachment in a safe location.

SEP SESAM SYSTEM RECOVERY PROCEDURE:

   1. Save the attachment (sesam_dr_info.ini file) from this email to the system you are using for
      SEP sesam Server recovery.

   2. Perform a clean installation of the SEP sesam Server to provide the required environment for
      restoring the server configuration and backup data

   3. Enable running SEP sesam commands globally from a terminal or command prompt (CMD) by setting up a
      SEP sesam profile. Start the recovery with the following command on the command line:
      sm_pysesam sesam_recover -f <path to sesam_dr_info.ini file>
      Replace <path to sesam_dr_info.ini file> with the path to the file saved in step 1.

EOF
   fi
else
   if [ "$lang" = "de" ]
   then
# Deutsch:
cat <<EOF > ${disaster_tmp_file}
Im Katastrophenfall wird der minimale SEP sesam Datenbankexport (Bootstrap-Datei) im Anhang benoetigt, um das
SEP sesam System wiederherzustellen. Er sollte ausschliesslich fuer die Wiederherstellung des SEP sesam
Systems verwendet werden.
Das SBC-Archiv der Konfigurationsdateien (sesam.ini.{.}.sbc) enthaelt die oeffentlichen SSH-Schluesseldateien,
die fuer den Zugriff auf die RDS erforderlich sind.
Sie sollten diese E-Mail und den Anhang an einem sicheren Ort speichern.

VORGEHENSWEISE ZUR WIEDERHERSTELLUNG DES SEP SESAM SYSTEMS:

   1. Speichern Sie den Anhang (Bootstrap-Datei und sesam.ini...sbc.gzip) aus dieser E-Mail auf dem System,
      das Sie fuer die SEP sesam Server Wiederherstellung verwenden.

   2. Neuinstallation des SEP sesam Servers und importieren der Bootstrap Datenbank:

      Windows
      =======
      i.  Doppelklicken Sie auf die SEP sesam Server Installationsdatei. Stimmen Sie der Lizenzvereinbarung
          zu und waehlen Sie die 'Desaster Wiederherstellung' im ersten Dialog aus.
      ii. Fahren Sie mit der Installation fort, bis Sie zum letzten Schritt
          'Bereit SEP sesam Server Version <Nummer> zu installieren' kommen.
          Unter der Option 'SEP sesam Server Datenbank importieren' klicken Sie auf 'Durchsuchen' und waehlen
          die in Schritt 1 gespeicherte Bootstrap-Datei aus, dann klicken Sie auf 'OK'.

      Linux
      =======
      i.  Installieren Sie den SEP sesam Server wie gewohnt.
      ii. Fuehren Sie den folgenden Befehl aus, um den Datenbankexport zu importieren:
             sm_db_update update -i <Pfad zur Bootstrap-Datei>

   3. Fuehren Sie die folgenden Befehle zum Austausch der Konfigurationsdateien aus:
          gzip -d -S gzip <Pfad zum gezippten SBC-Archiv>
          sbc -r -o over -s @<Pfad zum SBC-Archiv> -R /

   4. Verwenden Sie die CLI um die Selbstsicherung von SEP sesam zurueckzusichern:
          sm_cmd start restore -j SESAM_BACKUP -O o -a disaster_restore -R /

      Es werden die folgenden Einstellungen verwendet:
      - Der Zielpfad wird auf 'Auf Original-Zielpfad ruecksichern' gesetzt (-R /).
      - Die Ausfuehrungsoptionen sind auf 'Existierende Elemente ueberschreiben' eingestellt (-O o).
      - Die Wiederherstellung wird mit Relokation fuer die Datenbanksicherungsdatei ausgefuehrt,
        diese wird nach 'gv_rw_db:restore' zurueckgespielt.

   5. Sobald die Sicherung wiederhergestellt ist, wird als letzter Schritt die Datenbank ersetzt.

      Falls bei geoeffneter GUI der Dialog 'Disaster Restore abschliessen' mit der Frage, ob
      Sie die Datenbank automatisch importieren moechten erscheint, dann bestaetigen Sie mit 'OK'.
      Dadurch wird die Datenbankexportdatei geladen, die sich unter 'gv_rw_db:restore' befindet.
      Alternativ muessen Sie folgendes Kommando ausfuehren:
         sm_db_update update -d y

      Hinweis: Die GUI wird die Verbindung zum UI-Server voruebergehend verlieren.

EOF
   else 
# English:
cat <<EOF > ${disaster_tmp_file}
In the event of disaster, the SEP sesam database export in the attachment is needed to restore the SEP
sesam system. It should be used exclusively for SEP sesam system recovery.
The SBC archive of the configuration files (sesam.ini.{.}.sbc) contains the public SSH key files,
required for access to the RDS.
You should save this e-mail and the attachments in a safe location.

SEP SESAM SYSTEM RECOVERY PROCEDURE:

   1. Save the attachment (bootstrap file and sesam.ini...sbc.gzip) from this email to the system you want
      to use for SEP sesam Server recovery.

   2. Install the SEP sesam Server and import the bootstrap database:

      Windows
      =======
      i.  Double-click the SEP sesam Server installation file. Agree to the license agreement and check the
          'Disaster Recovery' box in the first dialog.
      ii. Continue with the installation until you get to the last step 'Ready to Install SEP sesam Server
          version <number>'. Under the option 'Import SEP sesam Server database' click 'Browse' and select
          the bootstrap file saved in step 1, then click 'OK'

      Linux
      =======
      i.  Install the SEP sesam Server as usual.
      ii. Execute the following command to import the database export:
             sm_db_update update -i <Path to bootstrap file>

   3. Execute the following commands to exchange the configuration files:
          gzip -d -S gzip <Path to the zipped SBC archive>
          sbc -r -o over -s @<Path to SBC archive> -R /

   4. Use the CLI to restore the self-backup of the SEP sesam. Execute the following command
          sm_cmd start restore -j SESAM_BACKUP -O o -a disaster_restore -R /

      The following settings are used:
      - The target path is set to 'Restore to original target path' (-R /).
      - The execution options are set to 'Overwrite existing items' (-O o).
      - The restore is executed with relocation for the database backup file,
        which is restored to 'gv_rw_db:restore'.

   5. Once the backup has been restored, the last step is to replace the database.

      If the GUI is open and the 'Complete the disaster restore' dialogue appears,
      asking whether you want to import the database automatically, confirm with 'OK'.
      This will load the database export file located under 'gv_rw_db:restore'.
      Alternatively, you must execute the following command:
         sm_db_update update -d y

      Note: The GUI will lose connection to the UI server.

EOF
   fi
fi

# This part is equal for minimal bootstrap db export file and cloud based disaster recovery 
if [ "$lang" = "de" ]
then
   # Deutsch:
cat <<EOF >> ${disaster_tmp_file}
-----------------------------------------------------------------------------

   Falls sich kein Anhang an dieser Email befindet ist ein Fehler aufgetreten. Details befinden sich in den log Dateien.
   DAS FEHLEN DES ANHANGS KANN ZU PROBLEMEN BEI DER SEP SESAM SYSTEM WIEDERHERSTELLUNG FUEHREN.

   Die nachfolgenden Informationen koennen zur Ruecksicherung des SESAM_BACKUPs verwendet werden,
   falls sich kein Anhang an dieser Email befindet.

      ${storageInfo}

   Ruecksicherungskommandozeile zur Wiederherstellung des SEP sesam Systems:

      ${restoreCmd}
EOF

   if [ -z "${attachment}" ]
   then
      mail_subject="SEP sesam Information zur DESASTER WIEDERHERSTELLUNG von ${gv_server} ${VERSION} IM FALLE VON HARDWARE ODER SOFTWARE DEFEKTEN - Achtung es befindet sich kein Anhang an dieser E-Mail!"
   else
      mail_subject="SEP sesam Information zur DESASTER WIEDERHERSTELLUNG von ${gv_server} ${VERSION} IM FALLE VON HARDWARE ODER SOFTWARE DEFEKTEN"
   fi
else
   # English:
cat <<EOF >> ${disaster_tmp_file}
-----------------------------------------------------------------------------

   If this e-mail does not contain an attachment an error occured. See log files for details.
   THE ABSENCE OF THE ATTACHMENT CAN LEAD TO PROBLEMS IN THE SEP SESAM SERVER RESTORE PROCEDURE.

   The following information can be used to restore the SESAM_BACKUP in case the attachment is missing.

      ${storageInfo}

   Restore command line to restore SEP sesam system:

      ${restoreCmd}

EOF

   if [ -z "${attachment}" ]
   then
      mail_subject="SEPsesam prepare for disaster Information of SEPsesam Server ${gv_server} Version ${VERSION} - Attention this email does not contain an attachment!"
   else
      mail_subject="SEPsesam prepare for disaster Information of SEPsesam Server ${gv_server} Version ${VERSION}"
   fi
fi

# 
# via SMTP interface with configured email account "sesam" in Sesam GUI
if [ -z "${attachment}" ]
then
   sm_smtp -A "sesam" -s "${mail_subject}" -M "${disaster_tmp_file}"
elif [ -z "${iniSbcFile}" ]
then
   sm_smtp -A "sesam" -s "${mail_subject}" -M "${disaster_tmp_file}" -a "${attachment}"
else
   sm_smtp -A "sesam" -s "${mail_subject}" -M "${disaster_tmp_file}" -a "${attachment}","${iniSbcFile}"
fi

