#!/bin/bash
# Podman Installation and Configuration Script for Archipelago
# Configures Podman for rootless operation

set -e

echo "🐳 Configuring Podman for rootless operation..."

# Ensure archipelago user exists
if ! id "archipelago" &>/dev/null; then
    echo "Creating archipelago user..."
    adduser -D -s /bin/bash archipelago
fi

# Create Podman configuration directories
mkdir -p /home/archipelago/.config/containers
mkdir -p /home/archipelago/.local/share/containers/storage

# Configure storage
cat > /home/archipelago/.config/containers/storage.conf <<EOF
[storage]
driver = "overlay"
runroot = "/run/user/$(id -u archipelago)/containers"
graphroot = "/home/archipelago/.local/share/containers/storage"
EOF

# Configure registries (use Docker Hub and quay.io)
mkdir -p /home/archipelago/.config/containers/registries.conf.d
cat > /home/archipelago/.config/containers/registries.conf.d/000-shortnames.conf <<EOF
[registries.search]
registries = ['docker.io', 'quay.io', 'ghcr.io']

[registries.insecure]
registries = []

[registries.block]
registries = []
EOF

# Set up subuid and subgid for rootless containers
if ! grep -q "^archipelago:" /etc/subuid; then
    echo "archipelago:100000:65536" >> /etc/subuid
fi

if ! grep -q "^archipelago:" /etc/subgid; then
    echo "archipelago:100000:65536" >> /etc/subgid
fi

# Create systemd user service directory
mkdir -p /home/archipelago/.config/systemd/user

# Enable lingering for archipelago user (allows user services to run without login)
loginctl enable-linger archipelago || true

# Set proper permissions
chown -R archipelago:archipelago /home/archipelago/.config
chown -R archipelago:archipelago /home/archipelago/.local

echo "✅ Podman configuration complete!"
