#!/usr/bin/env mana

if ($argv:n != 2)
  echo $argv:n
  echo "USAGE: delete_log_spacing (namebase) [test/commit]"
  break
end

# times scales:
# all for 2 days 
# 1/day for 1 week
# 1/week for 1 month
# 1/month for 1 year
# 1/quarter forever

$TIMEFORMAT = mjd
$TIMEREF = 2000/01/01,00:00:00

macro do_delete
  if ($0 != 3)
    echo "USAGE: do_delete (start) (stop)"
    break
  end

  local i

  list files -x "find . -maxdepth 1 -name '$argv:0\*' -cmin -$1 -cmin +$2 | sort"
  if ($files:n == 0)
    echo "no files in this date range, skipping"
    return
  end
  echo $files:0 $1 - $2
  list keep -add $files:0
  for i 1 $files:n
    echo rm $files:$i
    if ($commit)
      exec rm $files:$i
    end
  end
end

macro delete_log_spacing

  $keep:n = 0

  # keep 1/day for 1 week (stating 2 days ago)
  for dt 2 9
    echo "$dt days old (daily)"
    $dts = ($dt + 1)*1440
    $dte = ($dt + 0)*1440
    do_delete $dts $dte
  end

  # keep 1/week for 1 month (stating 9 days ago)
  for dt 9 37 7
    echo "$dt days old (weekly)"
    $dts = ($dt + 7)*1440
    $dte = ($dt + 0)*1440
    do_delete $dts $dte
  end

  # keep 1/month for 1 year (stating 39 days ago)
  for dt 37 397 30
    echo "$dt days old (monthly)"
    $dts = ($dt + 30)*1440
    $dte = ($dt +  0)*1440
    do_delete $dts $dte
  end

  echo "---- keeping these database copies ----"
  for i 0 $keep:n
    echo $keep:$i
  end
end

if ($SCRIPT)
  if ("$argv:1" == "commit") 
    $commit = 1
    delete_log_spacing
    exit 0
  end

  if ("$argv:1" == "test") 
    $commit = 0
    delete_log_spacing
    exit 0
  end

  echo "invalid option: use either 'test' or 'commit'"
  exit 0
end
