#!/bin/sh
set -e

echo "🔄 Alpine Init Replacement Starting..."

### **Step 1: Parse Kernel Command-Line Arguments**
DISK=""
IMAGE_URL=""
RESTORE=0
MOUNT_POINT="/mnt/newroot"

for arg in $(cat /proc/cmdline); do
    case "$arg" in
        restore=1) RESTORE=1 ;;
        IMAGE_URL=*) IMAGE_URL="${arg#IMAGE_URL=}" ;;
        DISK=*) DISK="${arg#DISK=}" ;;
    esac
done

# Ensure required parameters are set
if [ -z "$DISK" ]; then
    echo "❌ ERROR: DISK is not specified in kernel command line!"
    exit 1
fi

if [ "$RESTORE" -eq 1 ] && [ -z "$IMAGE_URL" ]; then
    echo "❌ ERROR: IMAGE_URL is not specified for restoration!"
    exit 1
fi

echo "📌 DISK: $DISK"
echo "📌 IMAGE_URL: $IMAGE_URL"
echo "📌 RESTORE: $RESTORE"

### **Step 2: Restore Image if Needed**
if [ "$RESTORE" -eq 1 ]; then
    echo "🔄 Downloading and Restoring Image..."

    # Detect compression type
    EXT="${IMAGE_URL##*.}"
    
    case "$EXT" in
        zst) wget -O - "$IMAGE_URL" | zstd -d | dd of="$DISK" bs=1M status=progress ;;
        xz)  wget -O - "$IMAGE_URL" | xz -d | dd of="$DISK" bs=1M status=progress ;;
        gz)  wget -O - "$IMAGE_URL" | gzip -d | dd of="$DISK" bs=1M status=progress ;;
        bz2) wget -O - "$IMAGE_URL" | bzip2 -d | dd of="$DISK" bs=1M status=progress ;;
        raw) wget -O - "$IMAGE_URL" | dd of="$DISK" bs=1M status=progress ;;
        *)   echo "❌ Unsupported image format: $EXT"; exit 1 ;;
    esac

    sync
    echo "✅ Restore Complete. Rebooting..."
    reboot
    exit 0
fi

