#!/bin/bash

. $script_path/functions.sh

echo "-- $0 --"

test_only='0'
test_dir="$HOME/tmp/gentoo"
#export http_proxy='10.0.2.2:3128'

if [ $test_only != '1' ]; then 
  . $script_path/functions.sh
fi

# todo:
# check default gw if is not present exit

destination=''
if [ $test_only == '1' ]; then
  destination=$test_dir
  if [ ! -d $destination ]; then
    mkdir -p $destination
  fi
else
  destination='/mnt/gentoo'
fi

# problem with detection with original location

export stage_prefix='stage3-i686'
#export stage_link='http://distfiles.gentoo.org/releases/x86/autobuilds/current-stage3/'
#export stage_link='http://ftp.linux.cz/pub/linux/gentoo/releases/x86/current-stage3/default/'
#export stage_link='http://ftp.linux.cz/pub/linux/gentoo/releases/x86/current-stage3/'
#export stage_link='http://127.0.0.2/share/gentoo/'
export stage_link='http://10.0.2.2/share/gentoo/'
cd $destination
wget -O start1.html $stage_link
build_day=$(grep folder.gif start1.html |sed -e 's/.*href="\([^"]*\)">.*/\1/')
#build_day=$(grep folder.png start1.html |sed -e 's/.*href="\([^"]*\)">.*/\1/')
wget -O start2.html $stage_link$build_day
for item in $(grep $stage_prefix start2.html | sed -e 's/.*href="\([^"]*\)">.*/\1/');
do
  echo "wget $stage_link$build_day$item"
  wget $stage_link$build_day$item
done
if [ $test_only != '1' ]; then
  rm start1.html start2.html
fi

#exit 0

if [ $test_only == '1' ]; then
  echo 'INFO: stage3 fetching only...'
else
  echo 'INFO: stage3 uncompressing...'
  #md5sum -c $stage_prefix*.tar.bz2.DIGESTS && tar xjpf $stage_prefix*
  #sha512sum -c $stage_prefix*.tar.bz2.DIGESTS && tar xjpf $stage_prefix*
  tar xjpf $stage_prefix*tar.bz2
fi

if [ $test_only == '1' ]; then
  echo 'INFO: stage3 fetching only...'
  if [ ! -d "$destination/usr" ]; then
    mkdir "$destination/usr"
  fi
else
  if [ ! -d "$destination/usr" ]; then
    echo 'ERROR: directory does not exists ', "$destination/usr"
    exit 1  
  fi
fi

cd "$destination/usr"
#portage_prefix='portage-latest.tar.bz2'
#portage_link='http://distfiles.gentoo.org/snapshots'
#portage_link='http://ftp.linux.cz/pub/linux/gentoo/snapshots'
#portage_link='http://127.0.0.2/share/gentoo'
portage_link='http://10.0.2.2/share/gentoo'
dwn_links=(portage-latest.tar.bz2 portage-latest.tar.bz2.gpgsig portage-latest.tar.bz2.md5sum)
for item in ${dwn_links[*]}
do
  echo "wget $portage_link/$item"
  wget "$portage_link/$item"
  if [ "$?" != "0" ]; then 
    wget "$portage_link/$item"
  fi
done

if [ $test_only == '1' ]; then
  echo 'INFO: portage fetching only...'
else
  echo 'INFO: portage uncompressing...'
  md5sum -c portage-latest.tar.bz2.md5sum && tar xjf portage-latest.tar.bz2
fi


if [ $test_only != '1' ]; then 
  done_mark
fi
