#!/usr/bin/perl
use strict;
use utf8;
use v5.10;

use File::Basename qw/ dirname basename /;
use File::Spec;
use Cwd qw/abs_path/;

our @INC;

BEGIN {
    push @INC, File::Spec->catdir( dirname( abs_path($0) ), '../lib' );
}

use SystemdService;
use Turnip;

my ( $normal, $early, $late ) = @ARGV;

Turnip->Initialize();

if ( -d $normal ) {
    if ( Turnip->hasCurrentTarget ) {
        my $current = Turnip->currentTarget;

        $current->WriteUnitFile(
            File::Spec->catfile( $normal, $current->unitFullName ) );

        say $_->WriteUnitFile(
            File::Spec->catfile( $normal, $_->unitFullName ) )
          for $current->services;

        my $wants = File::Spec->catdir( $normal, "multi-user.target.wants" );

        mkdir $wants unless -e $wants;

        symlink File::Spec->catfile( "..", $current->unitFullName ),
          File::Spec->catfile( $wants, $current->unitFullName );
    }
}
