#!/bin/bash
set -e

echo "=== Extracting Container Filesystem ==="

# Create output directory
mkdir -p build/container-filesystem

# Create a temporary container
echo "Creating temporary container from debian-atomic-installer:latest..."
TEMP_CONTAINER=$(podman create localhost/debian-atomic-installer:latest)
echo "Created container: $TEMP_CONTAINER"

# Export the entire container filesystem
echo "Exporting container filesystem..."
podman export $TEMP_CONTAINER | tar -C build/container-filesystem -xf -

# Clean up temporary container
echo "Cleaning up temporary container..."
podman rm $TEMP_CONTAINER

# Prepare the filesystem for live use
echo "Preparing filesystem for live system..."
cd build/container-filesystem

# Remove container-specific files
rm -f .dockerenv
rm -rf run/* tmp/* var/tmp/* || true

# Create essential mount points
mkdir -p proc sys dev run media/cdrom

# Create a proper systemd-based init
cat > sbin/init << 'EOF'
#!/bin/bash

# Mount essential filesystems if not already mounted
[ ! -d /proc/1 ] && mount -t proc proc /proc
[ ! -d /sys/kernel ] && mount -t sysfs sysfs /sys
[ ! -c /dev/null ] && mount -t devtmpfs devtmpfs /dev
[ ! -d /run/systemd ] && mount -t tmpfs tmpfs /run

# Start systemd as PID 1
if [ -x /usr/lib/systemd/systemd ]; then
    exec /usr/lib/systemd/systemd
else
    # Fallback to basic shell
    exec /bin/bash
fi
EOF

# Create autostart desktop entry for Calamares
mkdir -p etc/xdg/autostart
cat > etc/xdg/autostart/calamares.desktop << 'EOF'
[Desktop Entry]
Type=Application
Exec=calamares
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name[en_US]=Calamares Installer
Name=Calamares Installer
Comment[en_US]=System Installer
Comment=System Installer
EOF

# Configure LightDM for autologin
mkdir -p etc/lightdm/lightdm.conf.d
cat > etc/lightdm/lightdm.conf.d/50-calamares-autologin.conf << 'EOF'
[Seat:*]
autologin-user=installer
autologin-user-timeout=0
user-session=openbox
autologin-session=openbox
EOF

# Ensure OpenBox session is available
mkdir -p usr/share/xsessions
cat > usr/share/xsessions/openbox.desktop << 'EOF'
[Desktop Entry]
Name=Openbox
Comment=A lightweight window manager
Exec=openbox
Icon=openbox
Type=Application
EOF

# Create openbox session that launches Calamares
mkdir -p home/installer/.config/openbox
cat > home/installer/.config/openbox/autostart << 'EOF'
#!/bin/bash
# Auto-launch Calamares installer after desktop is ready
sleep 5
export DISPLAY=:0
# Create a prominent terminal for troubleshooting
xterm -geometry 120x30+100+100 -title "Debian Atomic Installer - Type 'calamares' to start installer" -fg white -bg black &
# Try to launch Calamares automatically
calamares &
EOF
chmod +x home/installer/.config/openbox/autostart

# Create OpenBox right-click menu
cat > home/installer/.config/openbox/menu.xml << 'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<openbox_menu xmlns="http://openbox.org/">
    <menu id="root-menu" label="Openbox 3">
        <item label="Launch Calamares Installer">
            <action name="Execute">
                <command>calamares</command>
            </action>
        </item>
        <item label="Open Terminal">
            <action name="Execute">
                <command>xterm</command>
            </action>
        </item>
        <separator />
        <item label="Restart">
            <action name="Execute">
                <command>reboot</command>
            </action>
        </item>
        <item label="Shutdown">
            <action name="Execute">
                <command>poweroff</command>
            </action>
        </item>
    </menu>
</openbox_menu>
EOF

# Create desktop shortcut for Calamares
mkdir -p home/installer/Desktop
cat > home/installer/Desktop/install-system.desktop << 'EOF'
[Desktop Entry]
Type=Application
Name=Install Debian Atomic Desktop
Comment=Install Debian Atomic Desktop to hard drive
Icon=calamares
Exec=calamares
Terminal=false
Categories=System;
EOF
chmod +x home/installer/Desktop/install-system.desktop

# Create a more visible desktop shortcut for terminal
cat > home/installer/Desktop/terminal.desktop << 'EOF'
[Desktop Entry]
Type=Application
Name=Terminal
Comment=Open Terminal
Icon=xterm
Exec=xterm -title "Installer Terminal - Type 'calamares' to launch installer"
Terminal=false
Categories=System;
EOF
chmod +x home/installer/Desktop/terminal.desktop

# Create a README on desktop
cat > home/installer/Desktop/README.txt << 'EOF'
=== Debian Atomic Desktop Installer ===

To launch the installer:
1. Right-click on desktop -> "Launch Calamares Installer"
2. Double-click "Install Debian Atomic Desktop" icon
3. Open terminal and type: calamares
4. Run the script: ./launch-installer.sh

If nothing appears, check the terminal for error messages.
EOF

# Create a simple script to launch Calamares manually
cat > home/installer/launch-installer.sh << 'EOF'
#!/bin/bash
echo "Starting Debian Atomic Desktop Installer..."
export DISPLAY=:0
calamares
EOF
chmod +x home/installer/launch-installer.sh

# Create xinitrc for proper X session
mkdir -p home/installer
cat > home/installer/.xinitrc << 'EOF'
#!/bin/bash
# Set proper environment
export DISPLAY=:0
export XDG_SESSION_TYPE=x11
export XDG_CURRENT_DESKTOP=openbox

# Start window manager in background
openbox &

# Start terminal for debugging
xterm -geometry 80x24+50+50 -title "Debian Atomic Installer Console" &

# Wait a moment for WM to start
sleep 3

# Launch Calamares
exec calamares
EOF
chmod +x home/installer/.xinitrc

# Create xsession that calls xinitrc
cat > home/installer/.xsession << 'EOF'
#!/bin/bash
exec /home/installer/.xinitrc
EOF
chmod +x home/installer/.xsession

# Set default systemd target to graphical
rm -f etc/systemd/system/default.target
ln -sf /usr/lib/systemd/system/graphical.target etc/systemd/system/default.target

# Create systemd service to launch Calamares after graphical session
mkdir -p etc/systemd/system
cat > etc/systemd/system/calamares-autostart.service << 'EOF'
[Unit]
Description=Auto-start Calamares Installer
After=graphical.target
Wants=graphical.target

[Service]
Type=simple
User=installer
Group=installer
Environment=DISPLAY=:0
ExecStartPre=/bin/sleep 10
ExecStart=/usr/bin/calamares
Restart=no

[Install]
WantedBy=graphical.target
EOF

# Enable the service by creating the wants directory and symlink
mkdir -p etc/systemd/system/graphical.target.wants
ln -sf /etc/systemd/system/calamares-autostart.service etc/systemd/system/graphical.target.wants/calamares-autostart.service

# Ensure proper ownership of installer user files
chown -R 1000:1000 home/installer/ || true

chmod +x sbin/init

# Create systemd symlink if it doesn't exist
if [ -x usr/lib/systemd/systemd ] && [ ! -L sbin/init.systemd ]; then
    ln -sf /usr/lib/systemd/systemd sbin/init.systemd
fi

echo "✅ Container filesystem extraction completed!"
echo "Filesystem size: $(du -sh . | cut -f1)"
echo "Files extracted to: $(pwd)"

cd ../..