#!/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      : 2017-05-16
# 
# ******************************************************************************
#
#  >>> This is a user-programmable procedure <<<
#
#  >>> Dies ist eine vom Benutzer programmierbare Prozedur <<<
#
# ******************************************************************************
# 
# Description :
#    This procedure is executed from a SEP sesam backup when the task name
#    contains "DISASTER" or "SESAM" (e.g., "SESAM_BACKUP") are detected.
#
#    These backups must be configured for disaster recovery, i.e., to save the
#    files that are needed to recover the SEP sesam Server itself. These are
#    all the files under the <SEP sesam home> and <SEP sesam home>\var\lis directory,
#    and the files in SEP sesam's database.
#
#    SEP sesam sends the media label with barcode of the used media
#    and a valid restore command to this procedure. Executing this command 
#    restores the file of the currently running backup to its original location.
#
#    It is strongly recommended to save several copies of this file to different
#    locations and ensure that it will be available in the event that the SEP sesam
#    server crashes. For example, you may save it to other computers within
#    your network or send it by email.
#
#    The values for the media label, backup source, barcode in case of a loader or
#    the value for the datastore path in case of a datastore as well as the restore 
#    command are as follows:
#
#         $1 = Media Label: {label}, Source: {backup source}, Barcode: {barcode}
#         oder
#         $1 = Datastore Path: {datastore path}
#         $2 = {sbc restore command}
#         $3 = {database export file name}
#
#    The example provided below will work if you configure the SEP sesam email for 
#    the account "sesam" (GUI menu: Configuration -> E-Mail settings -> Create new).
#    For details on disaster recovery procedure, check 
#    http://wiki.sepsoftware.com/wiki/index.php/Sesam_Disaster_Recovery_EN.
#
#    You can easily edit and modify the script according to your needs.
#
# ******************************************************************************
#
# Beschreibung 
#    Dieses Skript wird von SEP sesam nach einer Sicherung aufgerufen, falls der 
#    Auftragsname "DISASTER" oder "SESAM" beinhaltet (z.B. "SESAM_BACKUP").
#
#    Diese Sicherungen sind fuer einen Disaster Fall konfiguriert, d.h. sie sind dafuer
#    gedacht bei einem Ausfall des SEP Sesam Servers die notwendigen Daten 
#    wiederherstellt zu koennen. Es handelt sich hierbei um 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 Hautpordner 
#    abgelegt sind. Ausserdem sollte die Sesam Datenbank in der Sicherung enthalten sein.
#
#    Sesam sendet den Medienlabel und ggf. den Barcode des benutzten Mediums
#    und ein vollstaendiges Restaurierungskommando an diese Prozedur.
#    Startet man diese Prozedur von der Komandozeile, so werden alle Dateien
#    der gelaufenen Sicherung wieder an ihre urspruenglichen Plaetze zurueckkopiert.
#
#    Es wird dringend empfohlen mehrere Kopien der verschickten Datei an 
#    unterschiedlichen Orten aufzubewahren und sicher zu stellen dass sie im Falle
#    eines SEP sesam Server Ausfalls verfuegbar sind. Die Datei kann z.B. auf anderen
#    Computer im Netzwerk gespeichert oder per email versandt werden.
#
#    Die Werte fuer Medienlabel, Sicherungsquelle, Barcode im Falle eines Laders oder 
#    den Pfad des Datastore im Falle eines Datastores sowie den Ruecksicherungsbefehl 
#    selbst werden wie folgt uebergeben:
#
#         $1 = Media Label: {label}, Source: {backup source}, Barcode: {barcode}
#         oder
#         $1 = Datastore Path: {datastore path}
#         $2 = {sbc restore command}
#         $3 = {database export file name}      
# 
#    Das nachstehende Beispiel setzt voraus dass eine SEP sesam E-Mail mit dem
#    Benutzerkonto "sesam" bereits eingerichtet wurde (GUI Menue: Konfiguration -> 
#    E-Mail Einstellungen -> Neu) Naehere Details zum Thema Disaster Recovery finden
#    Sie unter http://wiki.sepsoftware.com/wiki/index.php/Sesam_Disaster_Recovery_EN.
#
#    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

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

storageInfo=$1
restoreCmd=$2

if [ "$lang" = "de" ]
then

cat <<EOF > ${gv_rw_work}/disaster.tmp
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 die Anhaenge an einem sicheren Ort speichern.

VORGEHENSWEISE ZUR WIEDERHERSTELLUNG DES SEP SESAM SYSTEMS:

   1. Speichern Sie den Anhang (Bootstrap-Datei) 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.

-----------------------------------------------------------------------------

   Falls sich kein Anhang an dieser Email befindet konnte der minimale Export Ihrer SEP sesam
   Datenbank nicht durchgefuehrt werden. Details befinden sich in den log Dateien.

   DAS FEHLEN DES MINIMALEN EXPORTS DER SEP sesam DATENBANK 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 "${sqlFile}" ]
   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 

cat <<EOF > ${gv_rw_work}/disaster.tmp
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) 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.

-----------------------------------------------------------------------------

   If this email does not contain an attachment, the minimal export of the SEP sesam database could not be 
   executed. See log files for details.

   THE ABSENCE OF A MINIMAL EXPORT OF THE SEP sesam DATABASE 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 "${sqlFile}" ]
   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 "${sqlFile}" ]
then
   sm_smtp -A "sesam" -s "${mail_subject}" -M "${gv_rw_work}/disaster.tmp"
else
   sm_smtp -A "sesam" -s "${mail_subject}" -M "${gv_rw_work}/disaster.tmp" -a "${sqlFile}","${iniFile}"
fi

