#!/bin/bash

# @file cw-flag
#
# Copyright (C) Metaswitch Networks 2017
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

# Utility script which allows semi-permanent flags to be set and cleared.

FLAG_DIR=/tmp/cw-flags
USAGE="Usage: flag {clear|set|read} <flag_name>" >&2
TIMEOUT_S=60

method=$1
flag_file=$FLAG_DIR/$2

# Clears the flag by removing the flag file.
clear_flag() {
  rm -f $flag_file
}

# Clears the flag if it has been set for longer than $TIMEOUT_S.
timeout_flag() {
  if [ -f $flag_file ]; then
    flag_time=$( expr `date +%s` - `stat -c %Y $flag_file` )
    if [ $flag_time -gt $TIMEOUT_S ]; then
      clear_flag
    fi
  fi
}

# Sets the flag by (re)creating the flag file.
set_flag() {
  mkdir -p $FLAG_DIR
  touch $flag_file
}

# Reads the flag, returning 1 if the flag is set and 0 if it is clear.
read_flag() {
  timeout_flag # Timeout the flag if necessary
  if [ -f $flag_file ]; then
    return 1
  else
    return 0
  fi
}

case "$method" in

  clear)
    clear_flag
    ;;

  set)
    set_flag
    ;;

  read)
    read_flag
    exit $?
    ;;

  *)
    echo $USAGE
    ;;

esac
