#!/bin/bash
#
# An Ansible module to disable/enable service restart
#  (including reload,stop and start)
# on apt install/reinstall for upgrade
# available for update.
#
# (c) Copyright 2015 Hewlett Packard Enterprise Development LP
# (c) Copyright 2017 SUSE LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

DOCUMENTATION = '''
---
module: service_restart
author: Therese McHale
short_description: Disables/Enables any restart type operations for upgrade
description:
    - On disable updates /etc/default/policy.rc.d with the service for which
      restart operations (including reload, stop and start) are to be disabled
    - On enable removes the service from /etc/default/policy.rc.d
options:
    service: <name of service>
    state: <enabled/disabled>
'''

EXAMPLES = '''
- service_restart:
     service: apache2
     state: disabled
'''

FILE="/etc/default/policy-rc.d"
function disable_service
{
  if service --status-all | grep -Fq $service ; then
     if grep -Fq $service $FILE ; then
       changed=false
       msg="$service already disabled"
     else
       sed -i 's/SERVICES="/SERVICES="'$service' /' $FILE
       changed="true"
       msg="Disabled $service"
     fi
  else
     changed="false"
     msg="service doesn't exist: $service"
  fi
}

function enable_service
{
  if service --status-all | grep -Fq $service ; then
     if  grep -Fq $service $FILE ; then
       sed -i 's/'$service' //'\g $FILE
       msg="Enabled $service"
       changed="true"
     else
       msg="$service already disabled"
       changed="false"
     fi
  else
     changed="false"
     msg="service doesn't exist: $service"
  fi
}
source $1
if [ -z "$service" ]; then
   printf '{"failed": "true", "msg": "missing required arguments: service"}'
   exit 1
fi

changed="false"
msg=""
contents=""
case $state in
    enabled)
       enable_service
       ;;
    disabled)
       disable_service
       ;;
    *)
       printf '{"failed": true, "msg": "invalid state: %s"}' "$state"
       exit 1
       ;;
esac
printf '{"changed": "%s", "msg": "%s"}' "$changed" "$msg"

exit 0
