#!/usr/bin/perl
# **** License ****
# Copyright (c) 2019, AT&T Intellectual Property. All rights reserved.
#
# Copyright (c) 2016 by Brocade Communications Systems, Inc.
# All rights reserved.
#
# SPDX-License-Identifier: GPL-2.0-only
#
# **** End License ****
#
use strict;
use warnings;
use lib '/opt/vyatta/share/perl5';

use Template;
use Getopt::Long;
use Vyatta::Config::Parse;

my $list_dir = "/etc/apt/sources.list.d";
my $pfx      = "system package repository";
my $archive;

sub archive_file() {
    return "$list_dir/$archive" . ".list";
}

sub generate {
    my $cfg = new Vyatta::Config::Parse("$pfx $archive");
    die("Unable to read [$pfx $archive] configuration\n")
      unless $cfg->{$archive};

    my $tt = new Template();
    $tt->process( \*DATA, { cfg => $cfg->{$archive} }, archive_file() )
      or die( $tt->error . "\n" );
    return;
}

sub remove {
    unlink( archive_file() );
    return;
}

sub usage {
    printf( "Usage for %s\n",        $0 );
    printf( "  %s --archive=name\n", $0 );
    exit(1);
}

GetOptions( "archive=s" => \$archive, )
  or usage();

generate() if $ENV{'COMMIT_ACTION'} eq 'ACTIVE';
generate() if $ENV{'COMMIT_ACTION'} eq 'SET';
remove()   if $ENV{'COMMIT_ACTION'} eq 'DELETE';

__END__
### Autogenerated by vyatta config system
### Note: Manual changes to this file will be lost during
###       the next commit.
[% url = cfg.url -%]
[% IF cfg.password.length > 0 || cfg.username.length > 0 -%]
[% url = url.replace('://', "://$cfg.username:$cfg.password@") -%]
[% END -%]
deb [% url %] [% cfg.distribution %] [% cfg.components %]
[% IF cfg.exists('sources') -%]
deb-src [% url %] [% cfg.distribution %] [% cfg.components %]
[% END -%]
