#!/bin/bash

set -e

service_directory="/etc/dinit.d"
logfile_directory="/var/log/dinit"
logfile_extenstion="log"

overwrite=false

while getopts ":o" opt; do
  case $opt in
    o)
      overwrite=true
      echo "Overwriting existing logfile specifications..."
      ;;
   \?)
     echo "Invalid option: -$OPTARG" >&2
     exit 1
     ;;
  esac
done

for file in "$service_directory"/* ; do
  if [[ -f "$file" ]]; then
    service_name=$(basename "$file") 
    if $overwrite; then
      echo "Removing logfile specification for $service_name"
      sudo sed -i '/^logfile/d' "$file"
    fi
    if ! grep -q "^logfile = \w+$" "$file"; then
      logfile_path="$logfile_directory/$service_name.$logfile_extenstion"
      echo "logfile = $logfile_path" | sudo tee -a "$file"
      echo "Added logfile $logfile_Path to service $service_name"
    else
      echo "Service $service_name already has logfile specified"
    fi
  fi
done
