#!/bin/sh -eu

# MIT License
#
# Copyright (c) 2017 Grigory Ustinov <grenka@altlinux.org>
# Copyright (c) 2017 Ivan Zakharyaschev <imz@altlinux.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

. dconf-locker-functions

checkPermissions()
{
    if ! [ -w "/etc/dconf/" ]; then
        echo "Error: There is not permission to write in /etc/dconf/ !"
        exit 2
    fi
}

printHelpMessage()
{
    echo \
"Usage: dconf-locker [-L] | [-l FILES...] |
                    [-U] | [-u FILES...] |
                    [-h]

        -L (--lockall)    - lock all dconf configurations
        -l (--locklist)   - lock a list of dconf configurations
        -U (--unlockall)  - unlock all dconf configurations
        -u (--unlocklist) - unlock list of dconf configurations

        -h (--help)       - show this text
"
}

if [ "$#" -eq 0 ]; then
    echo "Error: I need some arguments!"
    printHelpMessage
    exit 1
else
    checkPermissions
    case "$1" in
        -L|--lockall)
            if [ "$#" -eq 1 ]; then
                lock "all"
            else
                printHelpMessage
                exit 1
            fi
            ;;
        -l|--locklist)
            if [ "$#" -gt 1 ]; then
                lock "list" "$@"
            else
                printHelpMessage
                exit 1
            fi
            ;;
        -U|--unlockall)
            if [ "$#" -eq 1 ]; then
                unlock "all"
            else
                printHelpMessage
                exit 1
            fi
            ;;
        -u|--unlocklist)
            if [ "$#" -gt 1 ]; then
                unlock "list" "$@"
            else
                printHelpMessage
                exit 1
            fi
            ;;
        -h|--help)
            printHelpMessage
            exit 0
            ;;
        *) printHelpMessage
           exit 1
            ;;
    esac
fi
exit 0
