#!/bin/sh
echo "====================================================="
echo "    SITEFORGE INSTALLER (Installer version v0.1)     "
echo "====================================================="

echo "License store at: https://latinai.ch/shop"
read -p "Enter license key: " key
read -p "Enter installation path: " path

# Lizenzdatei-Pfad
license_file="$path/data/license.txt"

# Ordner sicherstellen
mkdir -p "$path/data"

# Lizenzdatei schreiben
echo "$key" > "$license_file"

# Lizenz prüfen
url="https://latinai.ch/wp-json/shoplicensegateway/license/validate/SF/$key"
response=$(curl -s --max-time 5 "$url")

# Prüfen ob JSON "status":"valid" enthält
echo "$response" | grep -q '"status":"valid"'
if [ $? -ne 0 ]; then
    echo "License invalid."

    # Ungültige Lizenz → Datei löschen
    rm -f "$license_file"

    exit 1
fi

echo "License validated successfully."

version="latest"
# Download update package
update_url="https://latinai.ch/wp-json/shoplicensegateway/updater/SF/update?version=$version&license_key=$key"
tmp_zip="/tmp/siteforge_update.zip"

curl -s -L "$update_url" -o "$tmp_zip"

if [ ! -f "$tmp_zip" ]; then
    echo "Failed to download update package."
    exit 1
fi

# Extract ZIP
unzip -q "$tmp_zip" -d /tmp/siteforge_update

# Copy contents of the inner folder "latinmagazine" into installation path
if [ -d "/tmp/siteforge_update/latinmagazine-release" ]; then
    cp -r /tmp/siteforge_update/latinmagazine-release/* "$path/"
else
    echo "Update package structure invalid."
    rm -f "$tmp_zip"
    exit 1
fi

# Cleanup
rm -rf /tmp/siteforge_update
rm -f "$tmp_zip"

echo "Update installed successfully."
