#! /usr/bin/env bash

# Copyright 2016 The Serviced Authors.
# 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. 

# this convenient script is intended to be run as SU by a cron job.
# It discards the blockes unused by the mounted dfs volumes of serviced
# It should not run more often than necessary.
# Please refer to the description of fstrim man page.
#
# Environment variable:
#     SERVICED (default: /opt/serviced/bin/serviced)
# 

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/serviced/bin:$PATH

err_exit()
{
   echo "Error: $1!" >&2
   exit 1
}

ok_exit()
{
   echo "Info:$1 ..." >&2
   exit 0
}

(( $EUID == 0 )) || err_exit "need to run as root"

# check dependency
for prog in fstrim "${SERVICED:=/opt/serviced/bin/serviced}"
do
    which "$prog" >/dev/null 2>&1 || err_exit "$prog not found"
done

# locate the thinpool
svc_vol_status=$("$SERVICED" volume status)                 || err_exit "serviced not returning volume status"
echo "$svc_vol_status" | grep -qE "Driver:\s+devicemapper"  || ok_exit  "serviced not running on devicemapper"
line=($(echo "$svc_vol_status" | grep -E "^Logical Volume:")) || err_exit "cannot find pool name"
pool_name=${line[2]}
[ -n $pool_name ]  || err_exit "cannot find pool name"

# fstrim only the mounted serviced volumes
# find the mount points on the thinpool
blk_devs=$(lsblk -n -o MOUNTPOINT,TYPE "/dev/mapper/$pool_name" | grep -E '/.+\s+dm')

# no need to fstrim if serviced volumes are not on device-mapper
(( $? == 0 )) || err_exit "No serviced data volumes on device-mapper"

for i in $(echo "$blk_devs" | cut -d ' ' -f 1)
do
    fstrim -v $i
done
