#!/usr/bin/env bash

# SPDX-License-Identifier: MIT

set -euo pipefail

root=${PLASMA_ALWAYS_SHOW_UNLOCK_ROOT:-/}
patch_file=${PLASMA_ALWAYS_SHOW_UNLOCK_PATCH:-/usr/share/plasma-always-show-unlock/LockScreenUi.patch}
target_dir="$root/usr/share/plasma/shells/org.kde.plasma.desktop"
target="$target_dir/contents/lockscreen/LockScreenUi.qml"

usage() {
    printf 'Usage: %s {apply|revert|status}\n' "${0##*/}" >&2
}

patch_options=(
    --silent
    --force
    --fuzz=0
    --no-backup-if-mismatch
    -p1
    -d "$target_dir"
)

run_patch() {
    patch "${patch_options[@]}" "$@" < "$patch_file"
}

check_patch() {
    run_patch --dry-run "$@" >/dev/null 2>&1
}

apply_patch() {
    if check_patch --reverse; then
        printf 'Plasma unlock prompt patch is already applied.\n'
        return
    fi
    if ! check_patch; then
        printf 'Error: %s is not a supported unmodified Plasma lock screen.\n' "$target" >&2
        return 1
    fi

    run_patch
    printf 'Applied the Plasma unlock prompt patch.\n'
}

revert_patch() {
    if check_patch; then
        printf 'Plasma unlock prompt patch is not applied.\n'
        return
    fi
    if ! check_patch --reverse; then
        printf 'Error: %s is neither the supported original nor patched file.\n' "$target" >&2
        return 1
    fi

    run_patch --reverse
    printf 'Reverted the Plasma unlock prompt patch.\n'
}

if (( $# != 1 )); then
    usage
    exit 2
fi

if [[ ! -f $target ]]; then
    printf 'Error: Plasma lock screen not found at %s.\n' "$target" >&2
    exit 1
fi
if [[ ! -r $patch_file ]]; then
    printf 'Error: patch file not found at %s.\n' "$patch_file" >&2
    exit 1
fi

case $1 in
    apply)
        apply_patch
        ;;
    revert)
        revert_patch
        ;;
    status)
        if check_patch --reverse; then
            printf 'Plasma unlock prompt patch is applied.\n'
        elif check_patch; then
            printf 'Plasma unlock prompt patch is not applied.\n'
            exit 1
        else
            printf 'Plasma lock screen is not supported by this patch.\n' >&2
            exit 2
        fi
        ;;
    *)
        usage
        exit 2
        ;;
esac
