#!/bin/sh
prefix=/usr/local
if test x"$1" = x"-h" -o x"$1" = x"--help" ; then
echo "Usage: ./configure [options]"
echo "  --help               print this message"
echo "  --prefix=PREFIX      default:/usr/local"
echo "  --bindir=BINDIR      default:$prefix/bin"
echo "  --datadir=BINDIR     default:$prefix/share"
echo ""
exit 1
fi

# parse options

for opt do
    optarg="${opt#*=}"
    case "$opt" in
        --prefix=*)
            prefix="$optarg"
            ;;
        --bindir=*)
            bindir="$optarg"
            ;;
        --datadir=*)
            datadir="$optarg"
            ;;
    esac
done

if test "z$bindir" = "z" 
then
    bindir=${prefix}/bin
fi

if test "z$datadir" = "z" 
then
    datadir=${prefix}/share
fi


# generate config files

cat > config.mak << EOF
prefix=$prefix
bindir=$bindir
datadir=$datadir
EOF

cat > config.h << EOF
#define IPIPDB_PATH "$datadir/17monipdb.dat"
EOF

cat > bin/nali << EOF
#!/bin/sh
if test \$# -gt 0
then
    echo \$@|perl $datadir/nali.pl
else
    perl $datadir/nali.pl
fi
EOF

cat > bin/nali-update << EOF
#!/bin/sh
ipipdb_dat_url="https://cdn.ipip.net/17mon/17monipdb.dat";
ipipdb_dat_local_path="$datadir/17monipdb.dat"
curl=\`which curl\`
wget=\`which wget\`

if ! test -w \$ipipdb_dat_local_path
then
    echo You may need sudo
    exit 1
fi

if test -f /tmp/17monipdb.dat
then
    rm -f /tmp/17monipdb.dat || exit 1
fi

if test "x\$curl" != "x" &&  test -x \$curl 
then
    command="\$curl -k --compressed \$ipipdb_dat_url -o /tmp/17monipdb.dat"
elif test "x\$wget" != "x" &&  test -x \$wget
then
    command="\$wget --no-check-certificate \$ipipdb_dat_url -O /tmp/17monipdb.dat"
else
    echo Error: Please install curl or wget
    exit 1
fi 
echo Updating \$ipipdb_dat_local_path
\$command && mv /tmp/17monipdb.dat \$ipipdb_dat_local_path && echo Successfully Updated && exit 0

echo Failed to update
exit 1
EOF

echo '***** Configure Successfully *****'
echo
echo "Install:"
echo 'make && make install'
echo 