#!/bin/sh

PRINTER_CFG="/usr/data/printer_data/config/printer.cfg"

if [ "x$1" = "xinstall" ]; then
    cd /usr/data
    [ ! -e module5d.tar ] && wget -O module5d.tar https://software.stereotech.org/5doe/master/creality-ender3-v3ke/mainsail/module5d.tar
    tar -xvf module5d.tar
    cp -r klipper/klippy/extras/. /usr/share/klipper/klippy/extras/
    cp klipper/module_5d.cfg /usr/data/printer_data/config/module_5d.cfg
    SAVE_CONFIG_MARKER='#*# <---------------------- SAVE_CONFIG ---------------------->'
    if grep -Fq "$SAVE_CONFIG_MARKER" "$PRINTER_CFG"; then
        awk -v marker="$SAVE_CONFIG_MARKER" '
            !inserted && index($0, marker) {
                print "[optional_rename module_5d]"
                print "check_path: /dev/serial/by-id/usb-Klipper_rp2040_512010725-if00"
                print "original_name: module_5d.cfg"
                print "[include module_*.cfg]"
                print ""
                inserted = 1
            }
            { print }
        ' "$PRINTER_CFG" > "${PRINTER_CFG}.tmp" && mv "${PRINTER_CFG}.tmp" "$PRINTER_CFG"
    else
        cat <<EOF >> "$PRINTER_CFG"
[optional_rename module_5d]
check_path: /dev/serial/by-id/usb-Klipper_rp2040_512010725-if00
original_name: module_5d.cfg
[include module_*.cfg]
EOF
    fi
    /etc/init.d/S55klipper_service restart
    [ ! -e /etc/init.d/S50nginx ] && mv nginx/S50nginx /etc/init.d/
    [ ! -e /etc/init.d/S56moonraker_service ] && mv moonraker/S56moonraker_service /etc/init.d/
    chmod +x /etc/init.d/S50nginx
    chmod +x /etc/init.d/S56moonraker_service
    chmod +x /usr/data/nginx/sbin/nginx
    /etc/init.d/S50nginx start
    /etc/init.d/S56moonraker_service start
    rm module5d.tar
elif [ "x$1" = "xuninstall" ]; then
    cd /overlay/upper
    /etc/init.d/S50nginx stop
    /etc/init.d/S56moonraker_service stop
    rm -rf /etc/init.d/S50nginx /etc/init.d/S56moonraker_service
    rm -rf /usr/data/printer_data/config/moonraker.conf /usr/data/printer_data/config/.moonraker.conf.bkp /usr/data/nginx /usr/data/moonraker /usr/data/mainsail
    rm -rf /usr/share/klipper/klippy/extras/module_5d* /usr/share/klipper/klippy/extras/optional_rename.py
    if [ -f "$PRINTER_CFG" ]; then
        sed -i '/\[optional_rename module_5d\]/,/^\[include module_\*\.cfg\]/d' "$PRINTER_CFG"
    fi
fi
