# Copyright 1999-2015. Parallels IP Holdings GmbH. All Rights Reserved.
package CompatArgParse;

#
# Old command-line parser. TODO: replace with standard Getopt::Long
#

sub parse {
  my ($ptrArgv,$ptrOpts) = @_;

  my (@keys, $firstKey, %prepKeys, $key, $value, $ptrArr, $arg, $state);
  my (%retHash, $pat, $found, $used, @rest, $fullArg, $prevKey);

  while (($key, $value) = each(%{$ptrOpts})) {
    @keys = split(/\|/, $key);
    $firstKey = $keys[0];
    $firstKey =~ s/^-*//;
    push @{$prepKeys{$firstKey}}, [@keys];
    push @{$prepKeys{$firstKey}}, $value;
  }

  $state = 0;
  foreach $arg (@{$ptrArgv}) {
    $used = 0;
    if ($state == 1) {
      if ($arg =~ /^-/) {
        $state = 0;
      } else {
        $used = 1;
        $retHash{$prevKey} = $arg;
        next;
      }
    }
    if ($state == 2) {
      $retHash{$prevKey} = $arg;
      $state = 0;
      $used = 1;
    } else {
      $fullArg = $arg;
      if ($arg =~ /^(-\S+)=(.+)/s) {
        $arg = $1;
        $value = $2;
      } else {
        $value = undef;
      }
      foreach $key (keys %prepKeys) {
        $ptrArr = $prepKeys{$key};
        $found = 0;
        foreach $pat (@{$ptrArr->[0]}) {
          if ($pat eq $arg) {
            $found = 1;
            last;
          }
        }
        if ($found) {
          $used = 1;
          if (defined($value)) {
            $retHash{$key} = $value;
          } else {
            if ($ptrArr->[1]) {
              if ($ptrArr->[1] =~ /\?$/) {
                $state = 1;
              } else {
                $state = 2;
              }
              $prevKey = $key;
            } else {
              $retHash{$key} = undef;
            }
          }
          last;
        }
      }
    }
    unless ($used) {
      if ($value) {
        push @rest, $fullArg;
      } else {
        push @rest, $arg;
      }
    }
  }
  @{$ptrArgv} = @rest;
  return \%retHash;
}

1;

# Local Variables:
# mode: cperl
# cperl-indent-level: 2
# indent-tabs-mode: nil
# tab-width: 4
# End:
