#!/bin/bash
set -e

case "$1" in
    configure)
        if ! id syncserver > /dev/null 2>&1; then
            useradd --system --no-create-home --shell /usr/sbin/nologin syncserver || true
        fi

        install -d -o syncserver -g syncserver -m 0750 /var/lib/syncserver/data || true
        install -d -o syncserver -g syncserver -m 0750 /var/lib/syncserver/ssh || true
        install -d -o syncserver -g syncserver -m 0750 /var/lib/syncserver/logs || true
        chown -R syncserver:syncserver /var/lib/syncserver
        install -d -o root -g root -m 0755 /etc/syncserver || true

        if [ ! -f /etc/syncserver/config.yaml ]; then
            cat > /etc/syncserver/config.yaml << 'EOF'
# SyncServer configuration
# Copy this file and edit as needed.
# Environment variables SYNCSERVER_* take precedence over this file.

data_dir: /var/lib/syncserver
addr: :8080

auth:
  jwt_secret: ""  # Leave empty to generate a random one on startup
  jwt_expiry_hours: 24

scheduler:
  timezone: UTC
EOF
            chown root:root /etc/syncserver/config.yaml
            chmod 0644 /etc/syncserver/config.yaml
        fi

        if command -v systemctl > /dev/null 2>&1; then
            systemctl daemon-reload 2>/dev/null || true
            systemctl enable syncserver.service 2>/dev/null || true
            systemctl try-restart syncserver.service 2>/dev/null || true
            if ! systemctl is-active --quiet syncserver.service; then
                systemctl start syncserver.service 2>/dev/null || true
            fi
        fi
        ;;

    abort-upgrade|abort-remove|abort-configure)
        exit 0
        ;;
esac

exit 0
