#!/bin/bash

if [ $# -ne 1 ]; then
        echo "Usage:$0 [errlog]"
        exit 1 
fi

errlog=$1
MIRROR_ROOT="/userdata/apt-mirror/mirror/mirrors.ustc.edu.cn/"

while read line; do
        while [ 0 ]; do
            echo ${line} | grep "Couldn't download package" | grep -q "http"
            if [ $? -eq 0 ]; then
                    findfail=1
                    break
            fi
            echo ${line} | grep "E: Failed to fetch" | grep -q "http"
            if [ $? -eq 0 ]; then
                    findfail=1
                    break
            fi
            findfail=0
            break
        done
    if [ ${findfail} -eq 0 ]; then
        continue
    fi
        pkgurl=$( echo $line | sed 's#^.*http#http#')   
        pkgurl=$( echo $pkgurl | sed -e 's#http://[^/]*/#https://mirror.tuna.tsinghua.edu.cn/#' -e 's/ .*$//' )    
        
        A1=${pkgurl#*//}
        url=${A1%%/*}
        pkgfullpath=${A1#*/}
        pkgpath=$(dirname ${pkgfullpath})
        pkgname=$(basename ${pkgfullpath})
        
        mkdir -p ${MIRROR_ROOT}/${pkgpath}
        if [ -f ${MIRROR_ROOT}/${pkgpath}/${pkgname} ]; then
                continue
        else
                cd ${MIRROR_ROOT}/${pkgpath}
                wget ${pkgurl} --output-document=${pkgname}
        fi

done < ${errlog}
