#!/usr/bin/perl
# vim: tabstop=2 smarttab expandtab softtabstop=2 shiftwidth=2
# in your vimrc, please add:
#   set modeline
#   set modelines=2

use strict;
use warnings;

BEGIN {
  use FindBin;
  do $FindBin::RealBin . '/../etc/config.pm' ;
}
my $dirTemp = MOUNT_DIR . '.tmp-cypher';
END {
  $dirTemp and -e $dirTemp and rmdir $dirTemp;
}

use Data::Dumper;
use Time::HiRes qw/time/;
use lib $FindBin::RealBin . '/../lib';
use tools;

-e $dirTemp and glob $dirTemp . '/*' and die "Unexpected: $dirTemp is not empty\n";

# the return code of system is not 0 when there is an error
system 'systemctl', 'is-active', FEATURE and die "Service is not active\n";
system 'systemctl', 'is-enabled', FEATURE and die "Service is not enabled\n";

-e $dirTemp or mkdir $dirTemp;

opendir my $dir, MOUNT_DIR or die $!;
while (my $fnm = readdir $dir) {
  $fnm =~ /^\.\.?$/ and next;
  my $src = MOUNT_DIR . '/' . $fnm;
  my $dst = $dirTemp . '/' . $fnm;
  printf "Moving '%s' to '%s'\n", $src, $dst;
  move($src, $dst);
}

system 'systemctl', 'disable', FEATURE and die "Can't disable service";
system 'systemctl', 'stop', FEATURE and die "Can't stop service";
my $t0 = time;
while (1) {
  sleep 1;
  system 'systemctl', 'is-active', FEATURE and last;
  time - $t0 >= 30 and die "Timeout stopping service " . FEATURE;
}
system 'umount', '-l', MOUNT_DIR;

opendir $dir, $dirTemp or die $dirTemp . ": $!";
while (my $fnm = readdir $dir) {
  $fnm =~ /^\.\.?$/ and next;
  my $src = $dirTemp . '/' . $fnm;
  my $dst = MOUNT_DIR . '/' . $fnm;
  printf "Move $src to $dst\n";
  
  move $src, $dst;
}
closedir $dir;

rmdir $dirTemp or warn "rmdir $dirTemp: $!";

