#!/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;

dieIfNotInactive FEATURE;
system 'umount', '-l', MOUNT_DIR;

-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);
}

my @filesCopied;
eval {
  my $t0 = time;
  system 'systemctl', 'start', FEATURE and die "Can't start service";
  while (1) {
    sleep 1;
    system 'systemctl', 'is-active', FEATURE or last;
    print "Service is not started\n";
    time - $t0 >= 30 and die "Timeout waiting for service " . FEATURE;
  }

  opendir my $dir, $dirTemp or die $!;
  while (my $fnm = readdir $dir) {
    $fnm =~ /^\.\.?$/ and next;
    my $src = $dirTemp . '/' . $fnm;
    my $dst = MOUNT_DIR . '/' . $fnm;
    printf "Copying '%s' to '%s'\n", $src, $dst;
    push @filesCopied, copy($src, $dst);
  }
};
$@ and do {
  my $msg = $@;
  chomp $msg;
  print "$msg\n";
  print "Rollback\n";
  system 'systemctl', 'stop', FEATURE;
  system 'umount', '-l', MOUNT_DIR;
  rmdir MOUNT_DIR;
  rmdir $dirTemp;
  exit 1;
};

for my $fnm (@filesCopied) {
  -d $fnm and do {
    rmdir $fnm or warn "Delete $fnm: $!";
    next;
  };
  unlink $fnm or warn "Delete $fnm: $!";
}

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

system 'systemctl', 'is-enabled', FEATURE or die "Service already enabled";
system 'systemctl', 'enable', FEATURE and die "Can't enable service";
