#!/bin/sh
# Move the accounts database

# Exit script with error if any of the commands below exit with error
set -xe

if [ "$UID" -eq 0 ] || ! loginctl; then
    echo "Running as root or no user sessions available, rescheduling to run later."
    exit 1
fi

# The database file leafname
DBNAME=accounts.db

echo "Moving accounts database for user $USER"

# The source directory containing the database
SOURCE=$HOME/.config/libaccounts-glib

# The destination to move the database to
DEST=$HOME/.local/share/system/privileged/Accounts/libaccounts-glib

echo "Moving from $SOURCE"
echo "Moving to $DEST"

# Check if it's already been moved
if [ -f "$DEST/$DBNAME" ]; then
    # This isn't an error, it mostly likely means it already moved
    echo "Skipping: accounts database already exists at $DEST/$DBNAME"
    return 0
fi

# Create a folder to contain the new database
mkdir -p $DEST

# Set appropriate directory ownership
# Note we start in the parent to capture the Accounts directory
chown -R $USER:privileged $DEST/..

# Check in case it's not yet been created
if [ ! -f "$SOURCE/$DBNAME" ]; then
    # This isn't an error, it might be a freshly flashed device
    echo "Skipping: accounts database not created at $SOURCE/$DBNAME"
    return 0
fi

# Backup the accounts database to the new location
ACCOUNTS=$SOURCE ag-backup
mv -n $SOURCE/$DBNAME.bak $DEST/$DBNAME

# Set appropriate file ownership and permissions
chown $USER:privileged $DEST/$DBNAME

# Remove the redirect file
rm -rf $DEST/accounts.redirect

# Remove the old database
rm -rf $SOURCE/

# The end
exit 0

