# Deploy memos (https://github.com/usememos/memos) — single-container
# self-hosted note server — to ana-docker.
#
# First-boot creates a fresh SQLite DB at /var/opt/memos/memos_prod.db
# inside the container (bind-mounted out to ${MEMOS_DATA_DIR} on the
# host). Visit http://10.250.50.70:5230 immediately after deploy to
# create the Host account.
#
# Usage:
#   scripts/elway ana-docker --playbook playbooks/deploy-memos.yaml
#
# Idempotent — safe to rerun.

vars:
  compose_dir: /opt/docker/compose/memos
  data_dir: /opt/docker/conf/memos/data
  host_port: "5230"

steps:
  # ── host-side dirs (sudo only on first run) ─────────────────────────

  - name: Ensure compose dir exists
    shell: mkdir -p {{ compose_dir }}
    sudo: true
    creates: "{{ compose_dir }}"

  - name: Chown compose dir to lkraven
    shell: chown -R lkraven:lkraven {{ compose_dir }}
    sudo: true
    when: "[ \"$(stat -c %U {{ compose_dir }})\" != \"lkraven\" ]"

  - name: Ensure data dir exists
    shell: mkdir -p {{ data_dir }}
    sudo: true
    creates: "{{ data_dir }}"

  - name: Chown data dir to lkraven
    shell: chown -R lkraven:lkraven {{ data_dir }}
    sudo: true
    when: "[ \"$(stat -c %U {{ data_dir }})\" != \"lkraven\" ]"

  # ── deploy compose + env ────────────────────────────────────────────

  - name: Upload compose.yaml
    upload:
      src: stacks/memos/compose.yaml
      dest: "{{ compose_dir }}/compose.yaml"
      mode: "0644"

  - name: Seed .env from template (only if absent)
    upload:
      src: stacks/memos/.env.example
      dest: "{{ compose_dir }}/.env"
      mode: "0644"
    when: "[ ! -f {{ compose_dir }}/.env ]"

  # ── bring up + wait ─────────────────────────────────────────────────

  - name: docker compose pull (gets latest stable tag)
    shell: |
      set -o pipefail
      cd {{ compose_dir }} && docker compose pull 2>&1 \
        | grep -vE '^(Status|Pulling) |Downloaded'

  - name: docker compose up -d
    shell: cd {{ compose_dir }} && docker compose up -d

  - name: Wait for / to respond
    shell: |
      for i in $(seq 1 30); do
        curl -sf -o /dev/null --max-time 3 http://localhost:{{ host_port }}/ && exit 0
        sleep 2
      done
      exit 1
    changed_when: "false"

verify:
  - name: / returns 200
    shell: curl -sf -o /dev/null http://localhost:{{ host_port }}/
    changed_when: "false"

  - name: Container is running
    shell: docker inspect memos --format '{{.State.Status}}' | grep -q running
    changed_when: "false"

  - name: Container is on traefik-net (so homepage docker discovery sees it)
    shell: docker inspect memos --format '{{json .NetworkSettings.Networks}}' | grep -q traefik-net
    changed_when: "false"
