# -*- mode: yaml; indent-tabs-mode: nil; tab-width: 2; coding: utf-8-unix -*-

---

- name: "proxy hourly.yml"
  debug:
    verbosity: 1
    msg: "proxy hourly.yml"

- block:

  - name: check privoxy is listening
    shell: |
      echo '{{ proxy_netstat_nlp_fact.stdout|default('')}}' | grep ':{{HTTP_PROXYPORT}}'
    ignore_errors: true # FixMe: defer to hourly.bash
    when:
      - HTTP_PROXYPORT != ''

  when:
    - PROXY_MODE in ['tor', 'whonix']
    - proxy_netstat_nlp_fact is defined and proxy_netstat_nlp_fact.rc == 0

- block:

  - name: "check dns is listening"
    shell: |
      # ip route | grep ^default || exit 0
      . /usr/local/etc/local.d/local.bash
      echo '{{ proxy_netstat_nlp_fact.stdout}}' | grep ':53' || { exit 1 ; }
      echo '{{proxy_netstat_nlp_fact.stdout}}' | grep ':{{PROXY_DNS_PORT}}' || {
        proxy_rc_service {{PROXY_DNS_PROXY}} status || proxy_rc_service {{PROXY_DNS_PROXY}} start || exit 1
        sleep 10
        netstat -nl -t inet | grep ':{{PROXY_DNS_PORT}}' && exit 0
        echo ERROR: {{PROXY_DNS_PROXY}} is not running
        exit 2
      }

    ignore_errors: true # FixMe: defer to hourly.bash
    when:
      - ansible_connection|default('') not in PLAY_NOSERVICE_CONNECTIONS
      - BOX_PROXY_MODE != 'nat'

  when:
    - PROXY_DNS_PROXY == "dnsmasq"
    - not ansible_check_mode
    - proxy_netstat_nlp_fact is defined

- name: check route
  shell: |
    ip route | grep default || \
      echo WARN: no default route

- name: check eix-update
  shell: |
    eix-update
  args:
    creates: /var/cache/eix/portage.eix
  when:
    - ansible_distribution == 'Gentoo'

- name: check resolv.conf
  shell: |
    grep 127.0.0.1 /etc/resolv.conf || {
      echo WARN: /etc/resolv.conf is not local
      echo nameserver 127.0.0.1 > /etc/resolv.conf
      }
    exit 0
  when:
    - PROXY_DNS_PROXY in ["pdnsd", "dnsmasq"]
    - not ansible_check_mode
    # - BASE_ARE_CONNECTED|default('') != ''

- name: check /etc/sysctl.conf
  shell: |
    cd /etc/sysctl.d
    cat *.conf | grep '^[a-z]' | while read elt rest ; do
        grep "^$elt" ../sysctl.conf && echo WARN: dup "^$elt" in ../sysctl.conf
      done
    exit 0

# This is dupped on daily/weekly/monthly
# [ $MYID -eq 0 ] || echo WARN: $prog should be run as root $MYID
- name: run proxy_hourly.bash
  environment: "{{ shell_proxy_env }}"
  shell: |
    umask 0027
    echo "INFO: proxy_log_hourly"
    cd {{USR_LOCAL}}/bin
    export MODE={{PROXY_MODE}}
    . proxy_export.bash
    [ -x proxy_hourly.bash ] || exit 0
    bash proxy_hourly.bash
  register: proxy_log_hourly
  notify: summary of logs
  when:
    - not ansible_check_mode
    - ansible_connection not in PLAY_CHROOT_CONNECTIONS
  # FixMe
  ignore_errors: true
