#!/bin/bash
# this script is run for each plugin during import snapshot or copy instances
# after files were copied from snapshot, but before start.sh is called

status() { echo "[INFO] $1" >> /var/log/ldap.log; }
 
BACKUP_DIR="/opt/backup"
CONFIG_LDIF="$BACKUP_DIR/config.ldif"
DATA_LDIF="$BACKUP_DIR/data.ldif"

if [ -f "$CONFIG_LDIF" ] && [ -f "$DATA_LDIF" ]; then
  rm -rf /var/lib/ldap/* /etc/ldap/slapd.d/*
  status "Cleaning backup files $CONFIG_LDIF and $DATA_LDIF..."
  /usr/local/bin/clean_backup_data_file.sh "$DATA_LDIF"

  status "Restoring configuration from $CONFIG_LDIF..."
  slapadd -n 0 -F /etc/ldap/slapd.d -l "$CONFIG_LDIF"

  status "Restoring data from $DATA_LDIF..."
  slapadd -n 1 -F /etc/ldap/slapd.d -l "$DATA_LDIF"

  status "Fixing permissions..."
  chown -R openldap:openldap /var/lib/ldap /etc/ldap/slapd.d

  mv "$CONFIG_LDIF" "$BACKUP_DIR/config.ldif.backup"
  mv "$DATA_LDIF" "$BACKUP_DIR/data.ldif.backup"
fi

# Safely set ownership on the directory itself, even if empty
chown -R openldap:openldap /etc/ldap/ssl

# Only attempt to change file permissions if files are actually present
if [ "$(ls -A /etc/ldap/ssl)" ]; then
    chmod 600 /etc/ldap/ssl/*.key 2>/dev/null
    chmod 644 /etc/ldap/ssl/*.crt 2>/dev/null
fi


