---
- name: deploy motief application
  hosts: sgeboers.nl
  remote_user: webapps

  tasks:
    - name: ensure git.sgeboers.nl SSH config uses port 222
      ansible.builtin.blockinfile:
        path: /home/webapps/.ssh/config
        create: yes
        mode: '0600'
        marker: "# {mark} ANSIBLE MANAGED: git.sgeboers.nl"
        block: |
          Host git.sgeboers.nl
            User git
            Port 222
            IdentityFile /home/webapps/.ssh/ed25519

    - name: ensure git.sgeboers.nl is in known_hosts
      ansible.builtin.known_hosts:
        name: "[git.sgeboers.nl]:222"
        key: "{{ lookup('pipe', 'ssh-keyscan -p 222 git.sgeboers.nl') }}"
        state: present

    - name: pull latest code
      ansible.builtin.git:
        repo: ssh://git@git.sgeboers.nl:222/sgeboers/motief.git
        dest: ~/motief
        clone: yes
        force: yes
        key_file: /home/webapps/.ssh/ed25519
        accept_newhostkey: yes

    - name: sync dependencies with uv
      ansible.builtin.shell:
        cmd: /home/webapps/.local/bin/uv sync
        chdir: ~/motief

    - name: stop existing streamlit process
      ansible.builtin.shell:
        cmd: pkill -f "streamlit run Home.py" || true
      ignore_errors: yes

    - name: ensure data directory exists on server
      ansible.builtin.file:
        path: /home/webapps/motief/data
        state: directory
        mode: '0755'

    - name: sync motions.db to server
      ansible.builtin.synchronize:
        src: ../data/motions.db
        dest: /home/webapps/motief/data/motions.db
        checksum: yes

    - name: start streamlit
      ansible.builtin.shell:
        cmd: nohup /home/webapps/.local/bin/uv run streamlit run Home.py --server.port=8501 --server.address=0.0.0.0 --server.headless=true --server.enableCORS=false &
        chdir: ~/motief

    - name: wait for streamlit to be ready
      ansible.builtin.uri:
        url: http://127.0.0.1:8501/_stcore/health
        method: GET
        status_code: 200
      retries: 30
      delay: 2
