#!/bin/sh

###############################################
# FUNCTIONS AND VARS
###############################################

OXI_INSTALL_DIR_NAME="@Oxibackup"
INSTALL_DIR="$SYNOPKG_PKGDEST_VOL/$OXI_INSTALL_DIR_NAME"
OXIBACKUP_SUB_DIR="$INSTALL_DIR/opt/oxibackup"
OXIBACKUP_OPT_DIR="/opt/oxibackup"

WS_URL="https://ws.oxibackup.eu"
DEP_FILES_URL="https://deploy.oxibox.com"

# Display a message  in final panel
_echosyno () {
    echo "$1<br/>" >> "$SYNOPKG_TEMP_LOGFILE"
}

# Echo in debug file
_echodebug () {
    echo "$1" >> "/var/log/oxibackup_install.log"
}

# Echo in both functions
_echo () {
    _echosyno "$1"
    _echodebug "$1"
}

###############################################

CURRENT_DATE=$(date)
_echodebug "Pre-installation started at $CURRENT_DATE"

###############################################


###############################################
# TEST CPU ARCH COMPATIBILITY
###############################################

ARCH=$(uname -m)
if [ "$ARCH" != "armv5tel" ] && [ "$ARCH" != "armv7l" ] && [ "$ARCH" != "aarch64" ] && [ "$ARCH" != "x86_64" ] && [ "$ARCH" != "i686" ]
then
    _echo "Incompatible NAS architecture detected: $ARCH"
    exit 1
fi


###############################################
# TEST SERVICE CONNECTIVITY
###############################################

_echodebug "Testing network access to Oxibox services..."

if ! command -v curl >/dev/null 2>&1
then
    if [ "$SYNOPKG_DSM_LANGUAGE" = "fre" ]
    then
        _echo "Curl est introuvable sur la machine"
    else
        _echo "Curl cannot be found"
    fi

    exit 1
fi

for TEST_URL in "$WS_URL" "$DEP_FILES_URL"
do
    CONN_TEST=$(curl "$TEST_URL")
    CONN_RESULT=$?
    if [ $CONN_RESULT -ne 0 ]
    then
        if [ "$SYNOPKG_DSM_LANGUAGE" = "fre" ]
        then
            if [ $CONN_RESULT -eq 6 ]
            then
                _echo "Erreur de résolution de nom. Veuillez vérifier vos paramètres réseau et DNS."
            else
                _echo "Impossible de joindre les services Oxibox. Veuillez vérifier vos paramètres réseau."
            fi
        else
            if [ $CONN_RESULT -eq 6 ]
            then
                _echo "Name resolution error. Please check your network and DNS settings."
            else
                _echo "Cannot join Oxibox services. Please check your network settings."
            fi
        fi

        exit 1
    fi
done

_echodebug "Done"

###############################################
# PREPARE INSTALLATION DIRECTORY
###############################################

_echodebug "Building Oxibackup installation directory..."

if ! mkdir -p "$OXIBACKUP_OPT_DIR" > /dev/null 2>&1
then
    if [ "$SYNOPKG_DSM_LANGUAGE" = "fre" ]
    then
        _echo "Une erreur est survenue lors de la création du répertoire d'installation de l'agent de sauvegarde Oxibox"
    else
        _echo "An error occurred while creating Oxibox backup agent installation directory"
    fi
fi
fusermount -u "$OXIBACKUP_OPT_DIR" > /dev/null 2>&1

# Remove existing directory if there's one and we're not upgrading
if [ "$SYNOPKG_PKG_STATUS" = "INSTALL" ] && [ -d "$INSTALL_DIR" ]
then
    if ! rm -rf "$INSTALL_DIR" > /dev/null 2>&1
    then
        if [ "$SYNOPKG_DSM_LANGUAGE" = "fre" ]
        then
            _echo "Le répertoire d'installation de l'agent Oxibox existe déjà et ne peut être supprimé"
        else
            _echo "Oxibox agent installation directory already exists and can't be removed"
        fi
        exit 1
    fi
fi
if ! mkdir -p "$OXIBACKUP_SUB_DIR" "$OXIBACKUP_SUB_DIR/tmp" > /dev/null 2>&1
then
    if [ "$SYNOPKG_DSM_LANGUAGE" = "fre" ]
    then
        _echo "Une erreur est survenue lors de la création du répertoire d'installation de l'agent de sauvegarde Oxibox dans le volume de destination"
    else
        _echo "An error occurred while creating Oxibox backup agent installation directories in the destination volume"
    fi
fi
chmod -R 755 "$INSTALL_DIR"
chmod 1777 "$OXIBACKUP_SUB_DIR/tmp"

if ! mount -o bind "$OXIBACKUP_SUB_DIR" "$OXIBACKUP_OPT_DIR" > /dev/null 2>&1
then
    _echodebug "An error occurred while trying to mount Oxibox backup agent installation directory"

    # Fall back to symlink
    if ! ln -sfn "$OXIBACKUP_SUB_DIR" "$OXIBACKUP_OPT_DIR" > /dev/null 2>&1
    then
        if [ "$SYNOPKG_DSM_LANGUAGE" = "fre" ]
        then
            _echo "Impossible de monter ou de créer un lien pour le répertoire d'installation de l'agent de sauvegarde Oxibox"
        else
            _echo "Unable to mount or link Oxibox backup agent installation directory"
        fi
        exit 1
    fi
fi

_echodebug "Done"


###############################################
# ADD ISRG ROOT X1 CERT
###############################################

CERT_URL="https://letsencrypt.org/certs/isrgrootx1.pem"
CERTS_FILE="/etc/ssl/certs/ca-certificates.crt"

if [ -f "$CERTS_FILE" ]
then
    _echodebug "Adding ISRG Root X1 certificate..."
    # Download cert
    X1_CERT=$(curl -sf "$CERT_URL")

    if [ ! -z "$X1_CERT" ]
    then
        # Get content for comparison (remove BEGIN and END lines)
        X1_CERT_CONTENT=$(echo "$X1_CERT" | grep -v CERTIFICATE)
        SEARCH=$(cat "$CERTS_FILE" | grep "$X1_CERT_CONTENT")

        if ! grep -q "$X1_CERT_CONTENT" "$CERTS_FILE" || [ "$X1_CERT_CONTENT" != "$SEARCH" ]
        then
            echo "$X1_CERT" >> "$CERTS_FILE"
            _echodebug "Done"
        fi
    else
        _echodebug "Could not get ISRG Root X1 certificate"
    fi
fi

exit 0
