#!/bin/bash

SKIP_HW_DESC_INIT=1
source /etc/mod-hardware-descriptor.env

# default vars values
ACTION=""
ADD_PLUGINS=false
ADD_DEV_CONF=false

function error {
    echo "$@" >/dev/stderr
}

# parse command line arguments
for arg in "$@"; do
    if [[ "${arg}" =~ ^backup$|^restore$ ]]; then
        ACTION=${arg}
    elif [[ "${arg}" =~ ^-[p|d] ]]; then
        if [[ "${arg}" == *"p"* ]]; then
            ADD_PLUGINS=true
        fi

        if [[ "${arg}" == *"d"* ]]; then
            ADD_DEV_CONF=true
        fi
    fi
done

# check if action argument is valid
if [[ -z "${ACTION}" ]]; then
    echo "Usage: $0 [OPTIONS] <backup|restore>"
    echo "  -p      add LV2 plugins to backup/restore"
    echo "  -d      add device configs (ALSA, bluetooth) to backup/restore"
    exit 2
fi

# get first pendrive in the list, partition #1
PENDRIVE_ID=$(ls /dev/disk/by-id/usb*-part1 2>/dev/null | head -1)

# no pendrive found
if [[ -z "${PENDRIVE_ID}" ]]; then
    error "no pendrive found"
    exit 100
fi

# create list of user files to copy
USER_FILES=(data/*.json keys .pedalboards)

# add plugins if required
if ${ADD_PLUGINS}; then
    USER_FILES+=(.lv2)
fi

# create list of device config files to copy
if ${ADD_DEV_CONF}; then
    DEV_CONFIG_FILES=(asound.state bluetooth)
fi

# mount pendrive
PENDRIVE=$(readlink -f ${PENDRIVE_ID})
mount ${PENDRIVE} /mnt
if [[ $? -ne 0 ]]; then
    # mount command prints an error message
    exit 101
fi

# backup files
if [[ "${ACTION}" == "backup" ]]; then
    # create destination directory
    mkdir -p /mnt/mod${PLATFORM}/

    # copy user data
    echo "creating user data backup"
    cd /root
    tar -cf /mnt/mod${PLATFORM}/user.tar ${USER_FILES[@]}

    # copy device data
    if ${ADD_DEV_CONF}; then
        echo "creating device data backup"
        cd /data
        tar -cf /mnt/mod${PLATFORM}/device.tar ${DEV_CONFIG_FILES[@]}
    fi

# restore files
else
    # check whether user backup exist
    if [[ ! -f /mnt/mod${PLATFORM}/user.tar ]]; then
        error "no user files found in the pendrive"
        umount /mnt
        exit 102
    fi

    # copy user data
    echo "restoring user data"
    tar -xf /mnt/mod${PLATFORM}/user.tar -C /root

    # check whether device config backup exist
    if ${ADD_DEV_CONF}; then
        if [[ -f /mnt/mod${PLATFORM}/device.tar ]]; then
            # copy device data
            echo "restoring device data"
            tar -xf /mnt/mod${PLATFORM}/device.tar -C /data
        else
            error "device.tar file not found in the pendrive"
            # does not exit if fail
        fi
    fi
fi

# sync and umount pendrive
echo "syncing data"
sync
umount /mnt

echo "done"
exit 0
