#!/bin/bash

# Set version variable for easy updates
VERSION="1.78"
JAR_SUFFIX="-SNAPSHOT-linux-aarch64.jar"

# Define remote hosts
ORDER1="kioskOrder1.local"
ORDER2="kioskOrder2.local"
COOK="kioskCook.local"
COOK2="kioskCook2.local"

# Define paths
LOCAL_PATH="/home/user/spagetka"
RESOURCE_SRC="$LOCAL_PATH/${VERSION}_resources"
RESOURCE_DEST="/home/user/spagetka/resources"
RESOURCE_ZIP="$LOCAL_PATH/${VERSION}_resources.zip"
PROPERTIES_FILE="$LOCAL_PATH/resources/application.properties"
REMOTE_PROPERTIES_FILE="$RESOURCE_DEST/application.properties"
CONFIG_FILE="$LOCAL_PATH/resources/config.json"
REMOTE_CONFIG_FILE="$RESOURCE_DEST/config.json"
TMP_PATCH_FILE="/tmp/static_json_patch.json"

CUSTOMER_PATCH=$(mktemp)
CASHIER_PATCH=$(mktemp)

# Define MySQL variables
DB_NAME="spagetka"

# Function to check SCP success
check_scp() {
    if [ $? -ne 0 ]; then
        echo "SCP failed. Aborting."
        exit 1
    fi
}

# Function to update properties file
update_properties_file() {
    local FILE_PATH="$1"
    local IS_REMOTE="$2"
    local HOST="$3"

    for KEY in "${!PROPERTIES_TO_SET[@]}"; do
        VALUE="${PROPERTIES_TO_SET[$KEY]}"

        if [ "$IS_REMOTE" = true ]; then
            ssh "$HOST" "grep -qE '^$KEY=' '$FILE_PATH'" 2>/dev/null
            if [ $? -eq 0 ]; then
                ssh "$HOST" "sed -i 's|^$KEY=.*|$KEY=$VALUE|' '$FILE_PATH'"
                echo "$HOST: Updated $KEY to $VALUE"
            else
                ssh "$HOST" "echo '$KEY=$VALUE' >> '$FILE_PATH'"
                echo "$HOST: Added $KEY=$VALUE"
            fi
        else
            if grep -qE "^$KEY=" "$FILE_PATH"; then
                sed -i "s|^$KEY=.*|$KEY=$VALUE|" "$FILE_PATH"
                echo "Local: Updated $KEY to $VALUE"
            else
                echo "$KEY=$VALUE" >> "$FILE_PATH"
                echo "Local: Added $KEY=$VALUE"
            fi
        fi
    done
}

update_json_section() {
    local FILE="$1"
    local SECTION="$2"
    local PATCH="$3"
    local TMPFILE="$(mktemp)"

    jq --argjson patch "$(cat "$PATCH")" \
       --arg section "$SECTION" \
       '.[$section] = (.[$section] * $patch)' \
       "$FILE" > "$TMPFILE" && mv "$TMPFILE" "$FILE"
}

# --- Ensure jq is installed remotely ---
ensure_jq_remote() {
    local HOST="$1"
    echo "Checking jq on $HOST..."
    ssh "$HOST" "command -v jq &>/dev/null || (echo 'Installing jq on $HOST...' && sudo apt-get update && sudo apt-get install -y jq)" || {
        echo "ERROR: Failed to install jq on $HOST."
        exit 1
    }
}

ensure_rsync_locally() {
    if ! command -v rsync &>/dev/null; then
    echo "rsync not found. Installing locally..."
    sudo apt-get update && sudo apt-get install -y rsync || {
        echo "ERROR: Failed to install rsync locally."
        exit 1
    }
    else
        echo "rsync already installed locally."
    fi
}

ensure_rsync_remote() {
    local HOST="$1"
    echo "Checking rsync on $HOST..."
    ssh "$HOST" "command -v rsync &>/dev/null || (echo 'Installing rsync on $HOST...' && sudo apt-get update && sudo apt-get install -y rsync)" || {
        echo "ERROR: Failed to install rsync on $HOST."
        exit 1
    }
}

# Copy JAR files
echo "Copying JAR files"
scp "$LOCAL_PATH/spagetka_CustomerApp-$VERSION$JAR_SUFFIX" "$ORDER1:$LOCAL_PATH" && check_scp
scp "$LOCAL_PATH/spagetka_CustomerApp-$VERSION$JAR_SUFFIX" "$ORDER2:$LOCAL_PATH" && check_scp
scp "$LOCAL_PATH/spagetka_CookApp-$VERSION$JAR_SUFFIX" "$COOK:$LOCAL_PATH" && check_scp
scp "$LOCAL_PATH/spagetka_CookApp-$VERSION$JAR_SUFFIX" "$COOK2:$LOCAL_PATH" && check_scp


if [[ ! -f "$RESOURCE_ZIP" ]]; then
    echo "WARNING: Zip file $RESOURCE_ZIP not found. Skipping resources backup and deployment."
else
    # Backup resources folder on all machines (including local)
    echo "Running resources backups"
    tar -czf "$LOCAL_PATH/resources_backup_$(date +%F_%H-%M-%S).tar.gz" -C "$LOCAL_PATH" resources
    ssh "$ORDER1" "tar -czf $LOCAL_PATH/resources_backup_$(date +%F_%H-%M-%S).tar.gz -C $RESOURCE_DEST ."
    ssh "$ORDER2" "tar -czf $LOCAL_PATH/resources_backup_$(date +%F_%H-%M-%S).tar.gz -C $RESOURCE_DEST ."
    ssh "$COOK" "tar -czf $LOCAL_PATH/resources_backup_$(date +%F_%H-%M-%S).tar.gz -C $RESOURCE_DEST ."
    ssh "$COOK2" "tar -czf $LOCAL_PATH/resources_backup_$(date +%F_%H-%M-%S).tar.gz -C $RESOURCE_DEST ."

    echo "Transferring resources (from zip)"
    ensure_rsync_locally()
    for HOST in "$ORDER1" "$ORDER2" "$COOK" "$COOK2"; do
        ensure_rsync_remote "$HOST"
    done

    TMPDIR=$(mktemp -d) || { echo "ERROR: Cannot create temp dir"; exit 1; }
    cleanup() { rm -rf "$TMPDIR"; }
    trap cleanup EXIT

    # Unpack the zip silently
    if ! unzip -q "$RESOURCE_ZIP" -d "$TMPDIR"; then
        echo "ERROR: Failed to unzip $RESOURCE_ZIP"
        exit 1
    fi

    # If the zip contains a single top-level directory, use its contents; otherwise use the root
    CONTENT_ROOT="$TMPDIR"
    mapfile -t entries < <(find "$TMPDIR" -mindepth 1 -maxdepth 1 -not -name '__MACOSX' -printf '%P\n')
    if (( ${#entries[@]} == 1 )) && [[ -d "$TMPDIR/${entries[0]}" ]]; then
        CONTENT_ROOT="$TMPDIR/${entries[0]}"
    fi

    # Local copy (preserves perms/timestamps)
    mkdir -p "$LOCAL_PATH/resources/"
    rsync -a "$CONTENT_ROOT"/ "$LOCAL_PATH/resources/"

    # Remote copy to each host (also preserves perms/timestamps)
    for HOST in "$ORDER1" "$ORDER2" "$COOK" "$COOK2"; do
        rsync -a "$CONTENT_ROOT"/ "$HOST:$RESOURCE_DEST" && check_scp
    done
fi

# Ensure logs directory exists on local and remote machines
LOGS_PATH="$LOCAL_PATH/logs/api"
mkdir -p "$LOGS_PATH"
ssh "$ORDER1" "mkdir -p $LOGS_PATH"
ssh "$ORDER2" "mkdir -p $LOGS_PATH"
ssh "$COOK" "mkdir -p $LOGS_PATH"
ssh "$COOK2" "mkdir -p $LOGS_PATH"

# Update scripts
echo "Running update of start scripts"
sed -i "s/spagetka_CashierApp-[0-9]*\.[0-9]*$JAR_SUFFIX/spagetka_CashierApp-$VERSION$JAR_SUFFIX/g" "$LOCAL_PATH/startCashier.sh" || echo "WARNING: Failed to update startCashier.sh"

ssh "$COOK" "sed -i 's/spagetka_CookApp-[0-9]*\.[0-9]*$JAR_SUFFIX/spagetka_CookApp-$VERSION$JAR_SUFFIX/g' $LOCAL_PATH/startCook.sh" || echo "WARNING: Failed to update startCook.sh for Cook"

ssh "$COOK2" "sed -i 's/spagetka_CookApp-[0-9]*\.[0-9]*$JAR_SUFFIX/spagetka_CookApp-$VERSION$JAR_SUFFIX/g' $LOCAL_PATH/startCook.sh" || echo "WARNING: Failed to update startCook.sh for Cook2"

ssh "$ORDER1" "sed -i 's/spagetka_CustomerApp-[0-9]*\.[0-9]*$JAR_SUFFIX/spagetka_CustomerApp-$VERSION$JAR_SUFFIX/g' $LOCAL_PATH/startCustomer.sh" || echo "WARNING: Failed to update startCustomer.sh for Order1"

ssh "$ORDER2" "sed -i 's/spagetka_CustomerApp-[0-9]*\.[0-9]*$JAR_SUFFIX/spagetka_CustomerApp-$VERSION$JAR_SUFFIX/g' $LOCAL_PATH/startCustomer.sh" || echo "WARNING: Failed to update startCustomer.sh for Order2"

# Properties
declare -A PROPERTIES_TO_SET=(
     [spagetka.promos.timeInterval]="900000"
)

# declare -A PROPERTIES_TO_SET=(
#     [property.key1]="value1"
#     [property.key2]="value2"
#     [property.key3]="value3 with spaces"
# )

if (( ${#PROPERTIES_TO_SET[@]} > 0 )); then
    # Update local application.properties
    echo "Updating local application.properties..."
    update_properties_file "$PROPERTIES_FILE" false ""

    # Update remote application.properties
    for HOST in "$ORDER1" "$ORDER2" "$COOK" "$COOK2"; do
        echo "Updating application.properties on $HOST..."
        update_properties_file "$REMOTE_PROPERTIES_FILE" true "$HOST"
    done
else
    echo "Skipping updates — PROPERTIES_TO_SET is empty."
fi

# # Update JSON files

# # --- Ensure jq is installed locally ---
# if ! command -v jq &>/dev/null; then
#     echo "jq not found. Installing locally..."
#     sudo apt-get update && sudo apt-get install -y jq || {
#         echo "ERROR: Failed to install jq locally."
#         exit 1
#     }
# else
#     echo "jq already installed locally."
# fi

# for HOST in "$ORDER1" "$ORDER2" "$COOK" "$COOK2"; do
#     ensure_jq_remote "$HOST"
# done

# # Local paths to temp JSON files
# CUSTOMER_PATCH=$(mktemp)
# CASHIER_PATCH=$(mktemp)

# # Define patches
# cat > "$CUSTOMER_PATCH" <<EOF
# {
#   "screensaverConfig" : {
#     "enableImageScreensaver": false,
#     "enableMediaScreensaver": false,
#     "relativeImagePath" : "/resources/screensaver/images",
#     "relativeMediaPath" : "/resources/screensaver/media",
#     "activationScreensaverTimeSeconds" : 120,
#     "nextImageTimeSeconds": 10,
#     "fadeOutTimeSeconds": 1,
#     "fadeInTimeSeconds": 1
#   }
# }
# EOF

# cat > "$CASHIER_PATCH" <<EOF
# {
#   "labelPrinterConfig": {
#     "enabled": false,
#     "printerName": "EML-300L",
#     "logoImageName": "spagetka_black_white_bg.png",
#     "codepage": "1250",
#     "font": 4,
#     "fontSize": 1,
#     "labelDimensions": {
#       "width": "50 mm",
#       "height": "50 mm",
#       "gapSize": "10.5 mm",
#       "gapOffset": "0 mm"
#     },
#     "referenceX": 0,
#     "referenceY": 0,
#     "speed": "6.0",
#     "density": 15,
#     "setPeel": "OFF",
#     "setCutter": "OFF",
#     "setPartialCutter": "OFF",
#     "setTear": "ON",
#     "setRibbon": "OFF",
#     "setDebug": "LABEL",
#     "direction": "0,0",
#     "shift": "0",
#     "offset": "0.0 mm",
#     "addCls": true,
#     "enabledCategories": [1, 2, 3, 8]
#   }
# }
# EOF

# echo "Updating local config.json..."
# update_json_section "$CONFIG_FILE" "customer" "$CUSTOMER_PATCH"
# update_json_section "$CONFIG_FILE" "cashier" "$CASHIER_PATCH"
# echo "Local update complete."

# # Update remote machines
# for HOST in "$ORDER1" "$ORDER2" "$COOK" "$COOK2"; do
#     echo "Updating config.json on $HOST..."

#     scp "$CUSTOMER_PATCH" "$HOST:/tmp/customer_patch.json"
#     scp "$CASHIER_PATCH" "$HOST:/tmp/cashier_patch.json"

#     ssh "$HOST" "jq -S --slurpfile patch /tmp/customer_patch.json \
#         '.customer = (.customer * \$patch[0])' '$REMOTE_CONFIG_FILE' > /tmp/tmp_config && mv /tmp/tmp_config '$REMOTE_CONFIG_FILE'"

#     ssh "$HOST" "jq -S --slurpfile patch /tmp/cashier_patch.json \
#         '.cashier = (.cashier * \$patch[0])' '$REMOTE_CONFIG_FILE' > /tmp/tmp_config && mv /tmp/tmp_config '$REMOTE_CONFIG_FILE'"

#     ssh "$HOST" "rm /tmp/customer_patch.json /tmp/cashier_patch.json"
#     echo "$HOST update complete."
# done

# # Clean up local temp files
# rm "$CUSTOMER_PATCH" "$CASHIER_PATCH"

CASHIER_PRINTER_NAME_RAW="$(jq -r '.cashier.printerConfig.printerName // empty' "$CONFIG_FILE")"

if [[ -z "$CASHIER_PRINTER_NAME_RAW" ]]; then
  CASHIER_PRINTER_NAME="'<empty>'"
else
  # Escape single quotes for SQL: ' -> ''
  CASHIER_PRINTER_NAME_ESC="${CASHIER_PRINTER_NAME_RAW//\'/\'\'}"
  CASHIER_PRINTER_NAME="'$CASHIER_PRINTER_NAME_ESC'"
fi

KIOSK_NAME_RAW=$(ssh user@kioskOrder1.local "jq -r '.common.kioskName // empty' '${REMOTE_CONFIG_FILE}'")

if [[ -z "$KIOSK_NAME_RAW" ]]; then
  KIOSK_NAME="'<empty>'"
else
  # Escape single quotes for SQL: ' -> ''
  KIOSK_NAME_ESC="${KIOSK_NAME_RAW//\'/\'\'}"
  KIOSK_NAME="'$KIOSK_NAME_ESC'"
fi

ENC_API_KEY_RAW="$(jq -r '.common.restClientConfig.encAPIKey // empty' "$CONFIG_FILE")"

if [[ -z "$ENC_API_KEY_RAW" ]]; then
  ENC_API_KEY="'<empty>'"
else
  # Escape single quotes for SQL: ' -> ''
  ENC_API_KEY_ESC="${ENC_API_KEY_RAW//\'/\'\'}"
  ENC_API_KEY="'$ENC_API_KEY_ESC'"
fi

CUSTOMER_PRINTER_NAME_RAW="$(jq -r '.customer.printerConfig.printerName // empty' "$CONFIG_FILE")"

if [[ -z "$CUSTOMER_PRINTER_NAME_RAW" ]]; then
  CUSTOMER_PRINTER_NAME="'<empty>'"
else
  # Escape single quotes for SQL: ' -> ''
  CUSTOMER_PRINTER_NAME_ESC="${CUSTOMER_PRINTER_NAME_RAW//\'/\'\'}"
  CUSTOMER_PRINTER_NAME="'$CUSTOMER_PRINTER_NAME_ESC'"
fi


# SQL section
SQL_COMMAND="
create table cook_config
(
    machine_id                         varchar(255) not null,
    version                            int          not null,
    colors__primary                    varchar(255) null,
    colors__primary_dark               varchar(255) null,
    colors__primary_hover              varchar(255) null,
    display_config__fullscreen         bit          null,
    display_config__resolution__height int          null,
    display_config__resolution__width  int          null,
    display_config__screen_id          int          null,
    open_scenic_view                   bit          null,
    serving_positions                  varchar(255) null,
    primary key (machine_id, version)
);

create table fonts_paths
(
    id            int          not null
        primary key,
    font_name     varchar(255) null,
    relative_path varchar(255) null
);

create table fonts_settings
(
    id           int          not null
        primary key,
    font_name    varchar(255) null,
    font_size    int          null,
    machine_id   varchar(255) null,
    setting_name varchar(255) null
);

create table cashier_config
(
    machine_id                                         varchar(255) not null,
    version                                            int          not null,
    colors__primary                                    varchar(255) null,
    colors__primary_dark                               varchar(255) null,
    colors__primary_hover                              varchar(255) null,
    display_config__fullscreen                         bit          null,
    display_config__resolution__height                 int          null,
    display_config__resolution__width                  int          null,
    display_config__screen_id                          int          null,
    download_partner_data                              bit          null,
    label_printer_config__add_cls                      bit          null,
    label_printer_config__codepage                     varchar(255) null,
    label_printer_config__density                      int          null,
    label_printer_config__direction                    varchar(255) null,
    label_printer_config__enabled                      bit          null,
    label_printer_config__enabled_categories           varchar(255) null,
    label_printer_config__font                         int          null,
    label_printer_config__font_size                    int          null,
    label_printer_config__label_dimensions__gap_offset varchar(255) null,
    label_printer_config__label_dimensions__gap_size   varchar(255) null,
    label_printer_config__label_dimensions__height     varchar(255) null,
    label_printer_config__label_dimensions__width      varchar(255) null,
    label_printer_config__logo_image_name              varchar(255) null,
    label_printer_config__offset                       varchar(255) null,
    label_printer_config__printer_name                 varchar(255) null,
    label_printer_config__reference_x                  int          null,
    label_printer_config__reference_y                  int          null,
    label_printer_config__set_cutter                   varchar(255) null,
    label_printer_config__set_debug                    varchar(255) null,
    label_printer_config__set_partial_cutter           varchar(255) null,
    label_printer_config__set_peel                     varchar(255) null,
    label_printer_config__set_ribbon                   varchar(255) null,
    label_printer_config__set_tear                     varchar(255) null,
    label_printer_config__shift                        varchar(255) null,
    label_printer_config__speed                        varchar(255) null,
    load_mock_data                                     bit          null,
    open_scenic_view                                   bit          null,
    printer_config__characters                         int          null,
    printer_config__codepage                           varchar(255) null,
    printer_config__enabled                            bit          null,
    printer_config__logo_image_name                    varchar(255) null,
    printer_config__printer_name                       varchar(255) null,
    primary key (machine_id, version)
);

create table common_config
(
    machine_id               varchar(255) not null,
    version                  int          not null,
    coffee_category_id       int          null,
    free_variant_price       double       null,
    fusilli_category_id      int          null,
    fusilli_ingredient_id    varchar(255) null,
    ice_cream_category_id    int          null,
    kiosk_name               varchar(255) null,
    rest_client__api_path    varchar(255) null,
    rest_client__base_url    varchar(255) null,
    rest_client__enc_api_key varchar(255) null,
    spaghetti_category_id    int          null,
    spaghetti_ingredient_id  varchar(255) null,
    primary key (machine_id, version)
);

create table customer_config
(
    machine_id                                              varchar(255) not null,
    version                                                 int          not null,
    always_fetch_from_db                                    bit          null,
    colors__main_background                               varchar(255) null,
    colors__popup_background                                varchar(255) null,
    colors__primary                                         varchar(255) null,
    colors__primary_dark                                    varchar(255) null,
    colors__primary_hover                                   varchar(255) null,
    declined_card_transaction_as_approved                   bit          null,
    display_config__fullscreen                              bit          null,
    display_config__resolution__height                      int          null,
    display_config__resolution__width                       int          null,
    display_config__screen_id                               int          null,
    download_partner_data                                   bit          null,
    load_mock_data                                          bit          null,
    mdb_config__baud_rate                                   int          null,
    mdb_config__bit_length                                  int          null,
    mdb_config__enabled                                     bit          null,
    mdb_config__port                                        varchar(255) null,
    mdb_config__stop_bits                                   int          null,
    open_scenic_view                                        bit          null,
    printer_config__characters                              int          null,
    printer_config__codepage                                varchar(255) null,
    printer_config__enabled                                 bit          null,
    printer_config__logo_image_name                         varchar(255) null,
    printer_config__paper_end_alarm_enabled                 bit          null,
    printer_config__printer_name                            varchar(255) null,
    printer_config__separate_order_number                   bit          null,
    reset_interval_seconds                                  int          null,
    screensaver_config__activation_screensaver_time_seconds int          null,
    screensaver_config__enable_image_screensaver            bit          null,
    screensaver_config__enable_media_screensaver            bit          null,
    screensaver_config__fade_in_time_seconds                double       null,
    screensaver_config__fade_out_time_seconds               double       null,
    screensaver_config__next_image_time_seconds             int          null,
    screensaver_config__relative_image_path                 varchar(255) null,
    screensaver_config__relative_media_path                 varchar(255) null,
    show_ingredients_in_product_detail                      bit          null,
    primary key (machine_id, version)
);

INSERT INTO spagetka.cook_config (machine_id, version, colors__primary, colors__primary_dark, colors__primary_hover, display_config__fullscreen, display_config__resolution__height, display_config__resolution__width, display_config__screen_id, open_scenic_view, serving_positions) VALUES ('kioskCook', 1, '#EFA941', '#D08E2D', '#F5B75B', true, 768, 1024, 2, true, '1');
INSERT INTO spagetka.cook_config (machine_id, version, colors__primary, colors__primary_dark, colors__primary_hover, display_config__fullscreen, display_config__resolution__height, display_config__resolution__width, display_config__screen_id, open_scenic_view, serving_positions) VALUES ('kioskCook2', 1, '#EFA941', '#D08E2D', '#F5B75B', true, 768, 1024, 2, true, '2');

INSERT INTO spagetka.fonts_paths (id, font_name, relative_path) VALUES (1, 'LobsterRegular', '/resources/fonts/Lobster-Regular.ttf');
INSERT INTO spagetka.fonts_paths (id, font_name, relative_path) VALUES (2, 'DejaVuSans', '/resources/fonts/DejaVuSans.ttf');

INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (1, 'DejaVuSans', 50, 'kioskCashier', 'title');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (2, 'DejaVuSans', 40, 'kioskCashier', 'subtitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (3, 'DejaVuSans', 28, 'kioskCashier', 'mainSceneButtons');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (4, 'DejaVuSans', 30, 'kioskCashier', 'orderManagementActionButtons');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (5, 'DejaVuSans', 20, 'kioskCashier', 'normal');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (6, 'DejaVuSans', 50, 'kioskCook', 'title');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (7, 'DejaVuSans', 40, 'kioskCook', 'subtitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (8, 'DejaVuSans', 25, 'kioskCook', 'topPanel');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (9, 'DejaVuSans', 20, 'kioskCook', 'orderItemTitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (10, 'DejaVuSans', 20, 'kioskCook', 'ingredientLabel');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (11, 'DejaVuSans', 20, 'kioskCook', 'locationLabel');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (12, 'DejaVuSans', 20, 'kioskCook', 'normal');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (13, 'DejaVuSans', 50, 'kioskCook2', 'title');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (14, 'DejaVuSans', 40, 'kioskCook2', 'subtitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (15, 'DejaVuSans', 25, 'kioskCook2', 'topPanel');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (16, 'DejaVuSans', 20, 'kioskCook2', 'orderItemTitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (17, 'DejaVuSans', 20, 'kioskCook2', 'ingredientLabel');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (18, 'DejaVuSans', 20, 'kioskCook2', 'locationLabel');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (19, 'DejaVuSans', 20, 'kioskCook2', 'normal');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (20, 'LobsterRegular', 50, 'kioskOrder1', 'title');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (21, 'LobsterRegular', 60, 'kioskOrder1', 'popupTitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (22, 'LobsterRegular', 40, 'kioskOrder1', 'subtitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (23, 'LobsterRegular', 30, 'kioskOrder1', 'priceLabel');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (24, 'LobsterRegular', 30, 'kioskOrder1', 'cartProductTitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (25, 'LobsterRegular', 22, 'kioskOrder1', 'cartAddItemsLabel');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (26, 'LobsterRegular', 16, 'kioskOrder1', 'cartQuantityLabel');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (27, 'DejaVuSans', 25, 'kioskOrder1', 'productTitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (28, 'DejaVuSans', 30, 'kioskOrder1', 'payByCashText');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (29, 'DejaVuSans', 20, 'kioskOrder1', 'normal');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (30, 'LobsterRegular', 200, 'kioskOrder1', 'confirmationOrderNumberFont');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (31, 'LobsterRegular', 80, 'kioskOrder1', 'welcomeMainTitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (32, 'LobsterRegular', 80, 'kioskOrder1', 'welcomeLogoTitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (33, 'LobsterRegular', 80, 'kioskOrder1', 'welcomeSubtitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (34, 'LobsterRegular', 50, 'kioskOrder2', 'title');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (35, 'LobsterRegular', 60, 'kioskOrder2', 'popupTitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (36, 'LobsterRegular', 40, 'kioskOrder2', 'subtitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (37, 'LobsterRegular', 30, 'kioskOrder2', 'priceLabel');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (38, 'LobsterRegular', 30, 'kioskOrder2', 'cartProductTitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (39, 'LobsterRegular', 22, 'kioskOrder2', 'cartAddItemsLabel');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (40, 'LobsterRegular', 16, 'kioskOrder2', 'cartQuantityLabel');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (41, 'DejaVuSans', 25, 'kioskOrder2', 'productTitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (42, 'DejaVuSans', 30, 'kioskOrder2', 'payByCashText');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (43, 'DejaVuSans', 20, 'kioskOrder2', 'normal');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (44, 'LobsterRegular', 200, 'kioskOrder2', 'confirmationOrderNumberFont');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (45, 'LobsterRegular', 80, 'kioskOrder2', 'welcomeMainTitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (46, 'LobsterRegular', 80, 'kioskOrder2', 'welcomeLogoTitle');
INSERT INTO spagetka.fonts_settings (id, font_name, font_size, machine_id, setting_name) VALUES (47, 'LobsterRegular', 80, 'kioskOrder2', 'welcomeSubtitle');

INSERT INTO spagetka.cashier_config (machine_id, version, colors__primary, colors__primary_dark, colors__primary_hover, display_config__fullscreen, display_config__resolution__height, display_config__resolution__width, display_config__screen_id, download_partner_data,
label_printer_config__add_cls, label_printer_config__codepage, label_printer_config__density, label_printer_config__direction, label_printer_config__enabled, label_printer_config__enabled_categories, label_printer_config__font, label_printer_config__font_size,
label_printer_config__label_dimensions__gap_offset, label_printer_config__label_dimensions__gap_size, label_printer_config__label_dimensions__height, label_printer_config__label_dimensions__width, label_printer_config__logo_image_name, label_printer_config__offset,
label_printer_config__printer_name, label_printer_config__reference_x, label_printer_config__reference_y, label_printer_config__set_cutter, label_printer_config__set_debug, label_printer_config__set_partial_cutter, label_printer_config__set_peel, label_printer_config__set_ribbon,
label_printer_config__set_tear, label_printer_config__shift, label_printer_config__speed, load_mock_data, open_scenic_view, printer_config__characters, printer_config__codepage, printer_config__enabled, printer_config__logo_image_name, printer_config__printer_name)
VALUES ('kioskCashier', 1, '#EFA941', '#D08E2D', '#F5B75B', true, 768, 1024, 0, true, true, '1250', 15, '0,0', true, '1, 2, 3, 8', 4, 1, '0 mm', '10.5 mm', '50 mm', '50 mm', 'spagetka_black_white_bg.png', '0.0 mm', 'EML-300L', 0, 0, 'OFF', 'LABEL', 'OFF', 'OFF', 'OFF',
'ON', '0', '6.0', false, false, 48, 'CP1250', true, 'spagetka-logo_black_200.png', ${CASHIER_PRINTER_NAME});

INSERT INTO spagetka.common_config (machine_id, version, coffee_category_id, free_variant_price, fusilli_category_id, fusilli_ingredient_id, ice_cream_category_id, kiosk_name, rest_client__api_path, rest_client__base_url, rest_client__enc_api_key, spaghetti_category_id, spaghetti_ingredient_id) 
VALUES ('kioskCashier', 1, 8, 10, 6, 'X2', 7, ${KIOSK_NAME}, '/api', 'https://partner.spagetka.eu', ${ENC_API_KEY}, 1, 'X1');
INSERT INTO spagetka.common_config (machine_id, version, coffee_category_id, free_variant_price, fusilli_category_id, fusilli_ingredient_id, ice_cream_category_id, kiosk_name, rest_client__api_path, rest_client__base_url, rest_client__enc_api_key, spaghetti_category_id, spaghetti_ingredient_id) 
VALUES ('kioskCook', 1, 8, 10, 6, 'X2', 7, ${KIOSK_NAME}, '/api', 'https://partner.spagetka.eu', ${ENC_API_KEY}, 1, 'X1');
INSERT INTO spagetka.common_config (machine_id, version, coffee_category_id, free_variant_price, fusilli_category_id, fusilli_ingredient_id, ice_cream_category_id, kiosk_name, rest_client__api_path, rest_client__base_url, rest_client__enc_api_key, spaghetti_category_id, spaghetti_ingredient_id) 
VALUES ('kioskCook2', 1, 8, 10, 6, 'X2', 7, ${KIOSK_NAME}, '/api', 'https://partner.spagetka.eu', ${ENC_API_KEY}, 1, 'X1');
INSERT INTO spagetka.common_config (machine_id, version, coffee_category_id, free_variant_price, fusilli_category_id, fusilli_ingredient_id, ice_cream_category_id, kiosk_name, rest_client__api_path, rest_client__base_url, rest_client__enc_api_key, spaghetti_category_id, spaghetti_ingredient_id) 
VALUES ('kioskOrder1', 1, 8, 10, 6, 'X2', 7, ${KIOSK_NAME}, '/api', 'https://partner.spagetka.eu', ${ENC_API_KEY}, 1, 'X1');
INSERT INTO spagetka.common_config (machine_id, version, coffee_category_id, free_variant_price, fusilli_category_id, fusilli_ingredient_id, ice_cream_category_id, kiosk_name, rest_client__api_path, rest_client__base_url, rest_client__enc_api_key, spaghetti_category_id, spaghetti_ingredient_id) 
VALUES ('kioskOrder2', 1, 8, 10, 6, 'X2', 7, ${KIOSK_NAME}, '/api', 'https://partner.spagetka.eu', ${ENC_API_KEY}, 1, 'X1');

INSERT INTO spagetka.customer_config (machine_id, version, always_fetch_from_db, colors__main_background, colors__popup_background, colors__primary, colors__primary_dark, colors__primary_hover, declined_card_transaction_as_approved, display_config__fullscreen, display_config__resolution__height,
display_config__resolution__width, display_config__screen_id, download_partner_data, load_mock_data, mdb_config__baud_rate, mdb_config__bit_length, mdb_config__enabled, mdb_config__port, mdb_config__stop_bits, open_scenic_view, printer_config__characters, printer_config__codepage,
printer_config__enabled, printer_config__logo_image_name, printer_config__paper_end_alarm_enabled, printer_config__printer_name, printer_config__separate_order_number, reset_interval_seconds, screensaver_config__activation_screensaver_time_seconds, screensaver_config__enable_image_screensaver,
screensaver_config__enable_media_screensaver, screensaver_config__fade_in_time_seconds, screensaver_config__fade_out_time_seconds, screensaver_config__next_image_time_seconds, screensaver_config__relative_image_path, screensaver_config__relative_media_path, show_ingredients_in_product_detail)
VALUES ('kioskOrder1', 1, true, '#FCF4D9', '#FCF4D9', '#EFA941', '#D08E2D', '#F5B75B', false, true, 1920, 1080, 0, true, false, 115200, 8, false, 'ttyMDB', 1, true, 48, 'CP1250', true, 'spagetka-logo_black_200.png', true, ${CUSTOMER_PRINTER_NAME}, true, 120, 120, true, false, 1, 1, 10, '/resources/screensaver/images',
'/resources/screensaver/media', false);
INSERT INTO spagetka.customer_config (machine_id, version, always_fetch_from_db, colors__main_background, colors__popup_background, colors__primary, colors__primary_dark, colors__primary_hover, declined_card_transaction_as_approved, display_config__fullscreen, display_config__resolution__height,
display_config__resolution__width, display_config__screen_id, download_partner_data, load_mock_data, mdb_config__baud_rate, mdb_config__bit_length, mdb_config__enabled, mdb_config__port, mdb_config__stop_bits, open_scenic_view, printer_config__characters, printer_config__codepage,
printer_config__enabled, printer_config__logo_image_name, printer_config__paper_end_alarm_enabled, printer_config__printer_name, printer_config__separate_order_number, reset_interval_seconds, screensaver_config__activation_screensaver_time_seconds, screensaver_config__enable_image_screensaver,
screensaver_config__enable_media_screensaver, screensaver_config__fade_in_time_seconds, screensaver_config__fade_out_time_seconds, screensaver_config__next_image_time_seconds, screensaver_config__relative_image_path, screensaver_config__relative_media_path, show_ingredients_in_product_detail)
VALUES ('kioskOrder2', 1, true, '#FCF4D9', '#FCF4D9', '#EFA941', '#D08E2D', '#F5B75B', false, true, 1920, 1080, 0, true, false, 115200, 8, false, 'ttyMDB', 1, true, 48, 'CP1250', true, 'spagetka-logo_black_200.png', true, ${CUSTOMER_PRINTER_NAME}, true, 120, 120, true, false, 1, 1, 10, '/resources/screensaver/images',
'/resources/screensaver/media', false);
"

if [ -n "$SQL_COMMAND" ]; then

    # Prompt for MySQL credentials
    echo -n "Enter MySQL username: "
    read -r DB_USER
    echo -n "Enter MySQL password: "
    read -s DB_PASS
    echo

    # Run SQL queries
    echo "Starting to run SQL commands"


    echo "$SQL_COMMAND" | mysql -u "$DB_USER" -p"$DB_PASS" "$DB_NAME"
    if [ $? -ne 0 ]; then
        echo "ERROR: SQL execution failed. Debugging information:"
        echo "$SQL_COMMAND"
        exit 1
    fi
else
    echo "Skipping SQL execution as no commands are provided."
fi

echo "Deployment completed successfully."