version = node.metadata['pleroma']['version']

users = {
    'pleroma': {
        'home': '/opt/pleroma',
    },
}

directories = {
    '/opt/pleroma': {},
    '/var/pleroma': {
        'owner': 'pleroma',
    },
    '/var/pleroma/uploads': {
        'owner': 'pleroma',
    },
    '/var/pleroma/static': {
        'owner': 'pleroma',
    },
    '/var/pleroma/static/emoji': {
        'owner': 'pleroma',
    },
}

if node.has_bundle('zfs'):
    directories['/var/pleroma']['needs'] = {
        'zfs_dataset:tank/pleroma-data',
    }

actions = {
    'pleroma_download_release': {
        'command': \
            'cd /opt/pleroma/ && '\
            f'wget -O/opt/pleroma/pleroma.zip https://git.pleroma.social/api/v4/projects/2/jobs/artifacts/release/{version}/download?job=amd64 && '\
            'rm -rf release && '\
            'unzip /opt/pleroma/pleroma.zip && '\
            'chown -R pleroma:pleroma /opt/pleroma/release && '\
            f'echo -n "{version}" > /opt/pleroma/.bundlewrap_installed_version',
        'unless': f'[ "$(cat /opt/pleroma/.bundlewrap_installed_version)" = "{version}" ]',
        'needs': {
            'directory:/opt/pleroma',
        },
        'preceded_by': {
            'svc_systemd:pleroma:stop',
        },
        'triggers': {
            'action:pleroma_migrate_database',
            'svc_systemd:pleroma:restart',
        },
    },
    'pleroma_migrate_database': {
        'triggered': True,
        'command': \
            'echo "CREATE EXTENSION IF NOT EXISTS citext;" | psql pleroma && '\
            'echo "CREATE EXTENSION IF NOT EXISTS pg_trgm;" | psql pleroma && '\
            'echo "CREATE EXTENSION IF NOT EXISTS \\\"uuid-ossp\\\";" | psql pleroma && '\
            'sudo -u pleroma PLEROMA_CONFIG_PATH=/opt/pleroma/pleroma.config.exs /opt/pleroma/release/bin/pleroma_ctl create',
        'needs': {
            'postgres_db:pleroma',
        },
    },
}

files = {
    '/etc/systemd/system/pleroma.service': {
        'triggers': {
            'action:systemd-reload',
            'svc_systemd:pleroma:restart',
        },
    },
    '/opt/pleroma/pleroma.config.exs': {
        'content_type': 'mako',
        'triggers': {
            'svc_systemd:pleroma:restart',
        },
    },
}

svc_systemd = {
    'pleroma': {
        'needs': {
            'action:pleroma_download_release',
            'action:pleroma_migrate_database',
            'file:/etc/systemd/system/pleroma.service',
            'file:/opt/pleroma/pleroma.config.exs',
        },
    },
}