#!/bin/bash

LAYEROPS_CONFIG_FILE={{ layerops_config_file }}
FSTAB_FILE={{ fstab_file }}

# Stop services
for service in \
  ly-tls-check.timer \
  consul-template-wg \
  consul-template-nomad-tags \
  nomad \
  clean-nomad \
  consul \
  "wg-quick@{{ wireguard_interface }}"
do
  systemctl disable --now $service
done

# Umount nomad alloc volumes
for i in $(mount |grep /data/nomad/alloc  | awk '{print $3}'); do umount $i; done

# Unmount layerops data dir if mounted
MOUNT_POINT={{ default_host_volume_path }}
mount | grep -q $MOUNT_POINT && umount $MOUNT_POINT

# Unmount shared volumes
SHARED_VOLUMES=$(jq -r '.sharedVolumes' $LAYEROPS_CONFIG_FILE)
for SHARED_VOLUME in $(echo "${SHARED_VOLUMES}" | jq -c '.[]')
do
  UUID=$(echo "${SHARED_VOLUME}" | jq -r .uuid)
  MOUND_DIR="/data/layerops/nfs/$UUID"

  grep -v "$MOUND_DIR" $FSTAB_FILE  > $FSTAB_FILE.tmp && mv $FSTAB_FILE.tmp $FSTAB_FILE
  umount $MOUND_DIR
done

# Delete layerops user
userdel --remove -f layerops

# Delete layerops directories
rm -fR \
  {{ layerops_data_path }} \
  {{ nomad_data_path }} \
  {{ nomad_log_path }} \
  {{ consul_data_path }} \
  {{ consul_log_path }} \
  {{ wireguard_config_path }} \
  {{ layerops_config_path }} \
  {{ systemd_resolve_config_dir }}/consul.conf \
  {{ layerops_sudoers_config_file }}

systemctl restart systemd-resolved

systemctl disable --now consul-template-instance-clean
