#!/usr/bin/env python3
"""Install reviewed R package sources using a local repository and no network."""
from pathlib import Path
import hashlib,json,os,shutil,subprocess,sys
root=Path(__file__).resolve().parents[1]
records=json.loads((root/'config/packages.json').read_text())
for record in records:
    path=root/'tools/vendor'/record['archive']
    if hashlib.sha256(path.read_bytes()).hexdigest()!=record['sha256']:sys.exit('Package source checksum changed: '+path.name)
rscript=os.environ.get('RSCRIPT') or shutil.which('Rscript') or '/opt/homebrew/opt/r/bin/Rscript'
library=root/'.R-library';repository=root/'.R-package-repository';contrib=repository/'src/contrib'
library.mkdir(exist_ok=True);contrib.mkdir(parents=True,exist_ok=True)
names='c('+','.join(json.dumps(r['package']) for r in records)+')'
check='.libPaths(c(commandArgs(TRUE)[1],.libPaths()));writeLines(vapply('+names+',function(p) packageDescription(p,fields="Version"),""))'
result=subprocess.run([rscript,'--vanilla','-e',check,str(library)],capture_output=True,text=True)
expected=[r['version'] for r in records]
if result.returncode==0 and result.stdout.strip().splitlines()==expected:
    print('Reviewed ggplot2 package versions already installed.');sys.exit(0)
for record in records:shutil.copy2(root/'tools/vendor'/record['archive'],contrib/record['archive'])
program='''a<-commandArgs(TRUE); tools::write_PACKAGES(a[2],type="source");
install.packages("ggplot2",lib=a[1],repos=paste0("file://",a[3]),type="source",Ncpus=2,quiet=TRUE)
'''
subprocess.run([rscript,'--vanilla','-e',program,str(library),str(contrib),str(repository)],check=True)
result=subprocess.run([rscript,'--vanilla','-e',check,str(library)],capture_output=True,text=True,check=True)
if result.stdout.strip().splitlines()!=expected:sys.exit('Installed package versions differ from reviewed sources')
print('Pinned R packages installed from the bundled local source repository.')
