#!/bin/bash -euf

# Copyright (C) 2021-2022 UBports Foundation.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Authored by: Ratchanan Srirattanamet <ratchanan@ubports.com>

set -o pipefail

# /com/lomiri/shell is omitted since its migration script ships with Lomiri.
# /com/lomiri/NotificationSettings is omitted since its migration script ships
# with lomiri-push-service.

DCONF_SOURCE_AND_TARGET_DIRS="\
/com/ubuntu/phone/ /com/lomiri/phone/
/com/ubuntu/sound/ /com/lomiri/sound/
/com/ubuntu/touch/sound/ /com/lomiri/touch/sound/
/com/ubuntu/touch/system/ /com/lomiri/touch/system/"

while read -r DCONF_SOURCE_DIR DCONF_TARGET_DIR; do
    # session-migration says we should be idempotent. We simply check if the target
    # is not empty as to not overwrite things that is set manually.
    target_content=$(dconf dump "$DCONF_TARGET_DIR")
    if [ -n "$target_content" ]; then
        echo "${DCONF_TARGET_DIR} is not empty. Perhaps the migration has already" \
            "happened, and/or the user has set additional settings."
        continue
    fi

    # Now, simply pipe the output of "dconf dump" to "dconf load". Won't wipe the
    # old data, in case the migration goes wrong.

    dconf dump "$DCONF_SOURCE_DIR" | dconf load "$DCONF_TARGET_DIR"
done <<<"${DCONF_SOURCE_AND_TARGET_DIRS}"

# Fixup hard-coded paths for call and message ringtones
for key in incoming-call-sound incoming-message-sound; do
    value=$(gsettings get com.lomiri.touch.sound $key)
    if [[ "$value" =~ ^/usr/share/sounds/ubuntu ]]; then
        value=${value/"/usr/share/sounds/ubuntu"/"/usr/share/sounds/lomiri"}
        gsettings set com.lomiri.touch.sound $key "$value"
    fi
done

echo "Migrated settings for miscellaneous Lomiri schemas."
