#!/macports/bin/bash

#
# change these to reflect your installation:
#
# prefix       : where you have installed macports
# macportsRoot : where you want to store the modifed Portfiles
#
#   ${1} :: type of conversion (hard|soft) (default:soft)
#   ${2} :: old version of Perl5 (default: 12)
#   ${3} :: new version of Perl5 (default: 16)
#

declare prefix='/macports'
declare macportsRoot='/Volumes/Bjarne/WebServer/MacPorts/portfiles'

declare type=${1:-soft}
declare -i versionOld=${2:-12}
declare -v versionNew=${3:-16}

# don't change this
declare rsyncMacportsOrg='/var/macports/sources/rsync.macports.org/release/tarballs/ports'

mkdir -pv ${macportsRoot}
declare -i counter=0
declare -i totalPorts=$( port -q list | wc -l )
declare -i portrev

#
# this time we're only interested in perl5.12
#

cd "${macportsRoot}"

#
# find all the ports that are dependent on perl5.${version}
# or p5.${version}-<something>
#
while read portname[0] portname[1] portname[2]
do
    (( counter++ ))
    printf "\r[ %5i | %5i ] %-50s" ${counter} ${totalPorts} ${portname[2]}
    fundet=$( \
        grep -E -e "(perl5.${version}|p5.${version})" $(port file ${portname[0]}) \
    |   wc -l )
    if [ ${fundet} -gt 0 ]
    then
        #
        # copy the Portfile
        #
        echo ''
        mkdir -p ${portname[2]}
        cd  ${portname[2]}
        cp  $(port file ${portname[0]}) 'Portfile.orig'

        #
        # splice the PortGroup command into the Portfile
        #
        portrev=$( grep -i "PortGroup.*perl5" 'Portfile.orig' | wc -l )
        if [ ${portrev} -eq 0 ]
        then
            sed -En -e "1,/^PortSystem/p" 'Portfile.orig' \
                >  'Portfile'
            echo -e "PortGroup        perl5  1.0" \
                >> 'Portfile'
            sed -E  -e "1,/^PortSystem/d" 'Portfile.orig' \
                >> 'Portfile'
        else
            cp 'Portfile.orig' 'Portfile'
        fi

        #
        # replace the hardcoded values
        #
        case ${type} in
        ( 'soft' )
            sed -i '' -E \
                -e "/^\#/!s/perl5.${versionOld}/perl\$\{perl5.major\}/g" \
                -e "/^\#/!s/p5.${versionOld}/p\$\{perl5.major\}/g" \
                'Portfile'
        ;;
        ( 'hard' )
        ;;
            sed -i '' -E \
                -e "/^\#/!s/perl5.${versionOld}/perl5.${versionNew}/g" \
                -e "/^\#/!s/p5.${versionOld}/p/5.${versionNew}g" \
                'Portfile'
        esac

        #
        # create *.diff files for all the copied Portfiles
        #
        rm 'patch-Portfile.diff' 2>/dev/null
        diff -u \
            $( port file ${portname[0]} ) \
            'Portfile' \
        > 'patch-Portfile.diff'

        cd ${OLDPWD}
    fi
done < <( port list )
printf "\r[ %5i | %5i ] %-50s\n" ${counter} ${totalPorts} '*** FINISHED ***'
