#!/bin/sh

set -eu

CONFIG_FILE=/etc/i-manager.conf

usage() {
    printf 'Использование: %s [--config FILE]\n' "$0"
}

while [ "$#" -gt 0 ]; do
    case "$1" in
        -c|--config)
            if [ "$#" -lt 2 ]; then
                printf 'Ошибка: после %s нужно указать файл конфигурации.\n' "$1" >&2
                exit 2
            fi
            CONFIG_FILE=$2
            shift 2
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        *)
            printf 'Неизвестный аргумент: %s\n' "$1" >&2
            usage >&2
            exit 2
            ;;
    esac
done

if [ ! -f "$CONFIG_FILE" ]; then
    printf 'Ошибка: файл конфигурации не найден: %s\n' "$CONFIG_FILE" >&2
    exit 1
fi

if [ ! -r "$CONFIG_FILE" ] || [ ! -w "$CONFIG_FILE" ]; then
    printf 'Ошибка: нет прав на чтение и запись файла: %s\n' "$CONFIG_FILE" >&2
    printf 'Запустите скрипт с подходящими правами, например через sudo.\n' >&2
    exit 1
fi

config_value() {
    awk -F= -v wanted="$1" '
        /^[[:space:]]*\[/ {
            section = $0
            sub(/^[[:space:]]*\[/, "", section)
            sub(/\][[:space:]]*$/, "", section)
            next
        }
        section == "display" {
            key = $1
            gsub(/^[[:space:]]+|[[:space:]]+$/, "", key)
            if (key == wanted) {
                value = substr($0, index($0, "=") + 1)
                gsub(/^[[:space:]]+|[[:space:]]+$/, "", value)
            }
        }
        END { print value }
    ' "$CONFIG_FILE"
}

current_type=$(config_value type)
current_reverse=$(config_value reverse)
case "$current_reverse" in
    true|TRUE|True|1|yes|YES|Yes) current_reverse=true ;;
    *) current_reverse=false ;;
esac

printf 'Текущая конфигурация: тип=%s, reverse=%s\n' \
    "${current_type:-не задан}" "$current_reverse"
printf '\nВыберите тип дисплея:\n'
printf '  1) SH1107\n'
printf '  2) SSD1306\n'
printf '  3) CH1115\n'

while :; do
    printf 'Номер [1-3]: '
    if ! IFS= read -r type_choice; then
        printf '\nОшибка: не удалось прочитать выбор.\n' >&2
        exit 1
    fi
    case "$type_choice" in
        1) display_type=sh1107; break ;;
        2) display_type=ssd1306; break ;;
        3) display_type=ch1115; break ;;
        *) printf 'Введите 1, 2 или 3.\n' ;;
    esac
done

while :; do
    printf 'Включить reverse? [y/N]: '
    if ! IFS= read -r reverse_choice; then
        printf '\nОшибка: не удалось прочитать выбор.\n' >&2
        exit 1
    fi
    case "$reverse_choice" in
        ''|n|N|no|NO|No|0|false|FALSE|False) display_reverse=false; break ;;
        y|Y|yes|YES|Yes|1|true|TRUE|True) display_reverse=true; break ;;
        *) printf 'Введите y или n.\n' ;;
    esac
done

tmp_file=$(mktemp "${CONFIG_FILE}.XXXXXX") || {
    printf 'Ошибка: не удалось создать временный файл рядом с конфигурацией.\n' >&2
    exit 1
}
trap 'rm -f "$tmp_file"' EXIT HUP INT TERM

if ! cp -p "$CONFIG_FILE" "$tmp_file"; then
    printf 'Ошибка: не удалось скопировать конфигурацию и сохранить её права доступа.\n' >&2
    exit 1
fi

if ! awk -v selected_type="$display_type" -v selected_reverse="$display_reverse" '
    function finish_display() {
        if (in_display) {
            if (!type_seen) print "type=" selected_type
            if (!reverse_seen) print "reverse=" selected_reverse
        }
    }
    /^[[:space:]]*\[/ {
        finish_display()
        section = $0
        sub(/^[[:space:]]*\[/, "", section)
        sub(/\][[:space:]]*$/, "", section)
        in_display = section == "display"
        if (in_display) {
            found_display = 1
            type_seen = 0
            reverse_seen = 0
        }
        print
        next
    }
    in_display && /^[[:space:]]*type[[:space:]]*=/ {
        if (!type_seen) print "type=" selected_type
        type_seen = 1
        next
    }
    in_display && /^[[:space:]]*reverse[[:space:]]*=/ {
        if (!reverse_seen) print "reverse=" selected_reverse
        reverse_seen = 1
        next
    }
    in_display && /^[[:space:]]*$/ {
        if (!type_seen) {
            print "type=" selected_type
            type_seen = 1
        }
        if (!reverse_seen) {
            print "reverse=" selected_reverse
            reverse_seen = 1
        }
        print
        next
    }
    { print }
    END {
        finish_display()
        if (!found_display) {
            if (NR > 0) print ""
            print "[display]"
            print "type=" selected_type
            print "reverse=" selected_reverse
        }
    }
' "$CONFIG_FILE" > "$tmp_file"; then
    printf 'Ошибка: не удалось подготовить обновлённую конфигурацию.\n' >&2
    exit 1
fi

mv "$tmp_file" "$CONFIG_FILE" || {
    printf 'Ошибка: не удалось обновить файл %s.\n' "$CONFIG_FILE" >&2
    exit 1
}

printf '\nСохранено: тип=%s, reverse=%s\n' "$display_type" "$display_reverse"
